| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675 |
- /*
- Jimp v0.10.2
- https://github.com/oliver-moran/jimp
- Ported for the Web by Phil Seaton
- MIT License
- Copyright (c) 2018 Oliver Moran
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in all
- copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- SOFTWARE.
- */
- if ((typeof(window)=='undefined' || !window) && (typeof(self)!='undefined')) var window = self;
- (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jimp = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
- function _arrayWithHoles(arr) {
- if (Array.isArray(arr)) return arr;
- }
- module.exports = _arrayWithHoles;
- },{}],2:[function(require,module,exports){
- function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) {
- for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
- arr2[i] = arr[i];
- }
- return arr2;
- }
- }
- module.exports = _arrayWithoutHoles;
- },{}],3:[function(require,module,exports){
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
- return self;
- }
- module.exports = _assertThisInitialized;
- },{}],4:[function(require,module,exports){
- function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
- }
- module.exports = _classCallCheck;
- },{}],5:[function(require,module,exports){
- var setPrototypeOf = require("./setPrototypeOf");
- function isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
- try {
- Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
- }
- function _construct(Parent, args, Class) {
- if (isNativeReflectConstruct()) {
- module.exports = _construct = Reflect.construct;
- } else {
- module.exports = _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
- return _construct.apply(null, arguments);
- }
- module.exports = _construct;
- },{"./setPrototypeOf":17}],6:[function(require,module,exports){
- function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
- module.exports = _createClass;
- },{}],7:[function(require,module,exports){
- function _defineProperty(obj, key, value) {
- if (key in obj) {
- Object.defineProperty(obj, key, {
- value: value,
- enumerable: true,
- configurable: true,
- writable: true
- });
- } else {
- obj[key] = value;
- }
- return obj;
- }
- module.exports = _defineProperty;
- },{}],8:[function(require,module,exports){
- function _getPrototypeOf(o) {
- module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
- }
- module.exports = _getPrototypeOf;
- },{}],9:[function(require,module,exports){
- var setPrototypeOf = require("./setPrototypeOf");
- function _inherits(subClass, superClass) {
- if (typeof superClass !== "function" && superClass !== null) {
- throw new TypeError("Super expression must either be null or a function");
- }
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
- }
- });
- if (superClass) setPrototypeOf(subClass, superClass);
- }
- module.exports = _inherits;
- },{"./setPrototypeOf":17}],10:[function(require,module,exports){
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- "default": obj
- };
- }
- module.exports = _interopRequireDefault;
- },{}],11:[function(require,module,exports){
- var _typeof = require("../helpers/typeof");
- function _getRequireWildcardCache() {
- if (typeof WeakMap !== "function") return null;
- var cache = new WeakMap();
- _getRequireWildcardCache = function _getRequireWildcardCache() {
- return cache;
- };
- return cache;
- }
- function _interopRequireWildcard(obj) {
- if (obj && obj.__esModule) {
- return obj;
- }
- if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
- return {
- "default": obj
- };
- }
- var cache = _getRequireWildcardCache();
- if (cache && cache.has(obj)) {
- return cache.get(obj);
- }
- var newObj = {};
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
- for (var key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
- if (desc && (desc.get || desc.set)) {
- Object.defineProperty(newObj, key, desc);
- } else {
- newObj[key] = obj[key];
- }
- }
- }
- newObj["default"] = obj;
- if (cache) {
- cache.set(obj, newObj);
- }
- return newObj;
- }
- module.exports = _interopRequireWildcard;
- },{"../helpers/typeof":20}],12:[function(require,module,exports){
- function _iterableToArray(iter) {
- if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
- }
- module.exports = _iterableToArray;
- },{}],13:[function(require,module,exports){
- function _iterableToArrayLimit(arr, i) {
- if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
- return;
- }
- var _arr = [];
- var _n = true;
- var _d = false;
- var _e = undefined;
- try {
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
- _arr.push(_s.value);
- if (i && _arr.length === i) break;
- }
- } catch (err) {
- _d = true;
- _e = err;
- } finally {
- try {
- if (!_n && _i["return"] != null) _i["return"]();
- } finally {
- if (_d) throw _e;
- }
- }
- return _arr;
- }
- module.exports = _iterableToArrayLimit;
- },{}],14:[function(require,module,exports){
- function _nonIterableRest() {
- throw new TypeError("Invalid attempt to destructure non-iterable instance");
- }
- module.exports = _nonIterableRest;
- },{}],15:[function(require,module,exports){
- function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance");
- }
- module.exports = _nonIterableSpread;
- },{}],16:[function(require,module,exports){
- var _typeof = require("../helpers/typeof");
- var assertThisInitialized = require("./assertThisInitialized");
- function _possibleConstructorReturn(self, call) {
- if (call && (_typeof(call) === "object" || typeof call === "function")) {
- return call;
- }
- return assertThisInitialized(self);
- }
- module.exports = _possibleConstructorReturn;
- },{"../helpers/typeof":20,"./assertThisInitialized":3}],17:[function(require,module,exports){
- function _setPrototypeOf(o, p) {
- module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
- }
- module.exports = _setPrototypeOf;
- },{}],18:[function(require,module,exports){
- var arrayWithHoles = require("./arrayWithHoles");
- var iterableToArrayLimit = require("./iterableToArrayLimit");
- var nonIterableRest = require("./nonIterableRest");
- function _slicedToArray(arr, i) {
- return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();
- }
- module.exports = _slicedToArray;
- },{"./arrayWithHoles":1,"./iterableToArrayLimit":13,"./nonIterableRest":14}],19:[function(require,module,exports){
- var arrayWithoutHoles = require("./arrayWithoutHoles");
- var iterableToArray = require("./iterableToArray");
- var nonIterableSpread = require("./nonIterableSpread");
- function _toConsumableArray(arr) {
- return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
- }
- module.exports = _toConsumableArray;
- },{"./arrayWithoutHoles":2,"./iterableToArray":12,"./nonIterableSpread":15}],20:[function(require,module,exports){
- function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
- function _typeof(obj) {
- if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
- module.exports = _typeof = function _typeof(obj) {
- return _typeof2(obj);
- };
- } else {
- module.exports = _typeof = function _typeof(obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
- };
- }
- return _typeof(obj);
- }
- module.exports = _typeof;
- },{}],21:[function(require,module,exports){
- module.exports = require("regenerator-runtime");
- },{"regenerator-runtime":332}],22:[function(require,module,exports){
- var Converter = require('./src/converter');
- /**
- * Function get source and destination alphabet and return convert function
- *
- * @param {string|Array} srcAlphabet
- * @param {string|Array} dstAlphabet
- *
- * @returns {function(number|Array)}
- */
- function anyBase(srcAlphabet, dstAlphabet) {
- var converter = new Converter(srcAlphabet, dstAlphabet);
- /**
- * Convert function
- *
- * @param {string|Array} number
- *
- * @return {string|Array} number
- */
- return function (number) {
- return converter.convert(number);
- }
- };
- anyBase.BIN = '01';
- anyBase.OCT = '01234567';
- anyBase.DEC = '0123456789';
- anyBase.HEX = '0123456789abcdef';
- module.exports = anyBase;
- },{"./src/converter":23}],23:[function(require,module,exports){
- 'use strict';
- /**
- * Converter
- *
- * @param {string|Array} srcAlphabet
- * @param {string|Array} dstAlphabet
- * @constructor
- */
- function Converter(srcAlphabet, dstAlphabet) {
- if (!srcAlphabet || !dstAlphabet || !srcAlphabet.length || !dstAlphabet.length) {
- throw new Error('Bad alphabet');
- }
- this.srcAlphabet = srcAlphabet;
- this.dstAlphabet = dstAlphabet;
- }
- /**
- * Convert number from source alphabet to destination alphabet
- *
- * @param {string|Array} number - number represented as a string or array of points
- *
- * @returns {string|Array}
- */
- Converter.prototype.convert = function(number) {
- var i, divide, newlen,
- numberMap = {},
- fromBase = this.srcAlphabet.length,
- toBase = this.dstAlphabet.length,
- length = number.length,
- result = typeof number === 'string' ? '' : [];
- if (!this.isValid(number)) {
- throw new Error('Number "' + number + '" contains of non-alphabetic digits (' + this.srcAlphabet + ')');
- }
- if (this.srcAlphabet === this.dstAlphabet) {
- return number;
- }
- for (i = 0; i < length; i++) {
- numberMap[i] = this.srcAlphabet.indexOf(number[i]);
- }
- do {
- divide = 0;
- newlen = 0;
- for (i = 0; i < length; i++) {
- divide = divide * fromBase + numberMap[i];
- if (divide >= toBase) {
- numberMap[newlen++] = parseInt(divide / toBase, 10);
- divide = divide % toBase;
- } else if (newlen > 0) {
- numberMap[newlen++] = 0;
- }
- }
- length = newlen;
- result = this.dstAlphabet.slice(divide, divide + 1).concat(result);
- } while (newlen !== 0);
- return result;
- };
- /**
- * Valid number with source alphabet
- *
- * @param {number} number
- *
- * @returns {boolean}
- */
- Converter.prototype.isValid = function(number) {
- var i = 0;
- for (; i < number.length; ++i) {
- if (this.srcAlphabet.indexOf(number[i]) === -1) {
- return false;
- }
- }
- return true;
- };
- module.exports = Converter;
- },{}],24:[function(require,module,exports){
- (function (global){
- 'use strict';
- var objectAssign = require('object-assign');
- // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
- // original notice:
- /*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
- * @license MIT
- */
- function compare(a, b) {
- if (a === b) {
- return 0;
- }
- var x = a.length;
- var y = b.length;
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i];
- y = b[i];
- break;
- }
- }
- if (x < y) {
- return -1;
- }
- if (y < x) {
- return 1;
- }
- return 0;
- }
- function isBuffer(b) {
- if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
- return global.Buffer.isBuffer(b);
- }
- return !!(b != null && b._isBuffer);
- }
- // based on node assert, original notice:
- // NB: The URL to the CommonJS spec is kept just for tradition.
- // node-assert has evolved a lot since then, both in API and behavior.
- // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
- //
- // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
- //
- // Originally from narwhal.js (http://narwhaljs.org)
- // Copyright (c) 2009 Thomas Robinson <280north.com>
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the 'Software'), to
- // deal in the Software without restriction, including without limitation the
- // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- // sell copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
- // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- var util = require('util/');
- var hasOwn = Object.prototype.hasOwnProperty;
- var pSlice = Array.prototype.slice;
- var functionsHaveNames = (function () {
- return function foo() {}.name === 'foo';
- }());
- function pToString (obj) {
- return Object.prototype.toString.call(obj);
- }
- function isView(arrbuf) {
- if (isBuffer(arrbuf)) {
- return false;
- }
- if (typeof global.ArrayBuffer !== 'function') {
- return false;
- }
- if (typeof ArrayBuffer.isView === 'function') {
- return ArrayBuffer.isView(arrbuf);
- }
- if (!arrbuf) {
- return false;
- }
- if (arrbuf instanceof DataView) {
- return true;
- }
- if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
- return true;
- }
- return false;
- }
- // 1. The assert module provides functions that throw
- // AssertionError's when particular conditions are not met. The
- // assert module must conform to the following interface.
- var assert = module.exports = ok;
- // 2. The AssertionError is defined in assert.
- // new assert.AssertionError({ message: message,
- // actual: actual,
- // expected: expected })
- var regex = /\s*function\s+([^\(\s]*)\s*/;
- // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
- function getName(func) {
- if (!util.isFunction(func)) {
- return;
- }
- if (functionsHaveNames) {
- return func.name;
- }
- var str = func.toString();
- var match = str.match(regex);
- return match && match[1];
- }
- assert.AssertionError = function AssertionError(options) {
- this.name = 'AssertionError';
- this.actual = options.actual;
- this.expected = options.expected;
- this.operator = options.operator;
- if (options.message) {
- this.message = options.message;
- this.generatedMessage = false;
- } else {
- this.message = getMessage(this);
- this.generatedMessage = true;
- }
- var stackStartFunction = options.stackStartFunction || fail;
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, stackStartFunction);
- } else {
- // non v8 browsers so we can have a stacktrace
- var err = new Error();
- if (err.stack) {
- var out = err.stack;
- // try to strip useless frames
- var fn_name = getName(stackStartFunction);
- var idx = out.indexOf('\n' + fn_name);
- if (idx >= 0) {
- // once we have located the function frame
- // we need to strip out everything before it (and its line)
- var next_line = out.indexOf('\n', idx + 1);
- out = out.substring(next_line + 1);
- }
- this.stack = out;
- }
- }
- };
- // assert.AssertionError instanceof Error
- util.inherits(assert.AssertionError, Error);
- function truncate(s, n) {
- if (typeof s === 'string') {
- return s.length < n ? s : s.slice(0, n);
- } else {
- return s;
- }
- }
- function inspect(something) {
- if (functionsHaveNames || !util.isFunction(something)) {
- return util.inspect(something);
- }
- var rawname = getName(something);
- var name = rawname ? ': ' + rawname : '';
- return '[Function' + name + ']';
- }
- function getMessage(self) {
- return truncate(inspect(self.actual), 128) + ' ' +
- self.operator + ' ' +
- truncate(inspect(self.expected), 128);
- }
- // At present only the three keys mentioned above are used and
- // understood by the spec. Implementations or sub modules can pass
- // other keys to the AssertionError's constructor - they will be
- // ignored.
- // 3. All of the following functions must throw an AssertionError
- // when a corresponding condition is not met, with a message that
- // may be undefined if not provided. All assertion methods provide
- // both the actual and expected values to the assertion error for
- // display purposes.
- function fail(actual, expected, message, operator, stackStartFunction) {
- throw new assert.AssertionError({
- message: message,
- actual: actual,
- expected: expected,
- operator: operator,
- stackStartFunction: stackStartFunction
- });
- }
- // EXTENSION! allows for well behaved errors defined elsewhere.
- assert.fail = fail;
- // 4. Pure assertion tests whether a value is truthy, as determined
- // by !!guard.
- // assert.ok(guard, message_opt);
- // This statement is equivalent to assert.equal(true, !!guard,
- // message_opt);. To test strictly for the value true, use
- // assert.strictEqual(true, guard, message_opt);.
- function ok(value, message) {
- if (!value) fail(value, true, message, '==', assert.ok);
- }
- assert.ok = ok;
- // 5. The equality assertion tests shallow, coercive equality with
- // ==.
- // assert.equal(actual, expected, message_opt);
- assert.equal = function equal(actual, expected, message) {
- if (actual != expected) fail(actual, expected, message, '==', assert.equal);
- };
- // 6. The non-equality assertion tests for whether two objects are not equal
- // with != assert.notEqual(actual, expected, message_opt);
- assert.notEqual = function notEqual(actual, expected, message) {
- if (actual == expected) {
- fail(actual, expected, message, '!=', assert.notEqual);
- }
- };
- // 7. The equivalence assertion tests a deep equality relation.
- // assert.deepEqual(actual, expected, message_opt);
- assert.deepEqual = function deepEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected, false)) {
- fail(actual, expected, message, 'deepEqual', assert.deepEqual);
- }
- };
- assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected, true)) {
- fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
- }
- };
- function _deepEqual(actual, expected, strict, memos) {
- // 7.1. All identical values are equivalent, as determined by ===.
- if (actual === expected) {
- return true;
- } else if (isBuffer(actual) && isBuffer(expected)) {
- return compare(actual, expected) === 0;
- // 7.2. If the expected value is a Date object, the actual value is
- // equivalent if it is also a Date object that refers to the same time.
- } else if (util.isDate(actual) && util.isDate(expected)) {
- return actual.getTime() === expected.getTime();
- // 7.3 If the expected value is a RegExp object, the actual value is
- // equivalent if it is also a RegExp object with the same source and
- // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
- } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
- return actual.source === expected.source &&
- actual.global === expected.global &&
- actual.multiline === expected.multiline &&
- actual.lastIndex === expected.lastIndex &&
- actual.ignoreCase === expected.ignoreCase;
- // 7.4. Other pairs that do not both pass typeof value == 'object',
- // equivalence is determined by ==.
- } else if ((actual === null || typeof actual !== 'object') &&
- (expected === null || typeof expected !== 'object')) {
- return strict ? actual === expected : actual == expected;
- // If both values are instances of typed arrays, wrap their underlying
- // ArrayBuffers in a Buffer each to increase performance
- // This optimization requires the arrays to have the same type as checked by
- // Object.prototype.toString (aka pToString). Never perform binary
- // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
- // bit patterns are not identical.
- } else if (isView(actual) && isView(expected) &&
- pToString(actual) === pToString(expected) &&
- !(actual instanceof Float32Array ||
- actual instanceof Float64Array)) {
- return compare(new Uint8Array(actual.buffer),
- new Uint8Array(expected.buffer)) === 0;
- // 7.5 For all other Object pairs, including Array objects, equivalence is
- // determined by having the same number of owned properties (as verified
- // with Object.prototype.hasOwnProperty.call), the same set of keys
- // (although not necessarily the same order), equivalent values for every
- // corresponding key, and an identical 'prototype' property. Note: this
- // accounts for both named and indexed properties on Arrays.
- } else if (isBuffer(actual) !== isBuffer(expected)) {
- return false;
- } else {
- memos = memos || {actual: [], expected: []};
- var actualIndex = memos.actual.indexOf(actual);
- if (actualIndex !== -1) {
- if (actualIndex === memos.expected.indexOf(expected)) {
- return true;
- }
- }
- memos.actual.push(actual);
- memos.expected.push(expected);
- return objEquiv(actual, expected, strict, memos);
- }
- }
- function isArguments(object) {
- return Object.prototype.toString.call(object) == '[object Arguments]';
- }
- function objEquiv(a, b, strict, actualVisitedObjects) {
- if (a === null || a === undefined || b === null || b === undefined)
- return false;
- // if one is a primitive, the other must be same
- if (util.isPrimitive(a) || util.isPrimitive(b))
- return a === b;
- if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
- return false;
- var aIsArgs = isArguments(a);
- var bIsArgs = isArguments(b);
- if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
- return false;
- if (aIsArgs) {
- a = pSlice.call(a);
- b = pSlice.call(b);
- return _deepEqual(a, b, strict);
- }
- var ka = objectKeys(a);
- var kb = objectKeys(b);
- var key, i;
- // having the same number of owned properties (keys incorporates
- // hasOwnProperty)
- if (ka.length !== kb.length)
- return false;
- //the same set of keys (although not necessarily the same order),
- ka.sort();
- kb.sort();
- //~~~cheap key test
- for (i = ka.length - 1; i >= 0; i--) {
- if (ka[i] !== kb[i])
- return false;
- }
- //equivalent values for every corresponding key, and
- //~~~possibly expensive deep test
- for (i = ka.length - 1; i >= 0; i--) {
- key = ka[i];
- if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
- return false;
- }
- return true;
- }
- // 8. The non-equivalence assertion tests for any deep inequality.
- // assert.notDeepEqual(actual, expected, message_opt);
- assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
- if (_deepEqual(actual, expected, false)) {
- fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
- }
- };
- assert.notDeepStrictEqual = notDeepStrictEqual;
- function notDeepStrictEqual(actual, expected, message) {
- if (_deepEqual(actual, expected, true)) {
- fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
- }
- }
- // 9. The strict equality assertion tests strict equality, as determined by ===.
- // assert.strictEqual(actual, expected, message_opt);
- assert.strictEqual = function strictEqual(actual, expected, message) {
- if (actual !== expected) {
- fail(actual, expected, message, '===', assert.strictEqual);
- }
- };
- // 10. The strict non-equality assertion tests for strict inequality, as
- // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
- assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
- if (actual === expected) {
- fail(actual, expected, message, '!==', assert.notStrictEqual);
- }
- };
- function expectedException(actual, expected) {
- if (!actual || !expected) {
- return false;
- }
- if (Object.prototype.toString.call(expected) == '[object RegExp]') {
- return expected.test(actual);
- }
- try {
- if (actual instanceof expected) {
- return true;
- }
- } catch (e) {
- // Ignore. The instanceof check doesn't work for arrow functions.
- }
- if (Error.isPrototypeOf(expected)) {
- return false;
- }
- return expected.call({}, actual) === true;
- }
- function _tryBlock(block) {
- var error;
- try {
- block();
- } catch (e) {
- error = e;
- }
- return error;
- }
- function _throws(shouldThrow, block, expected, message) {
- var actual;
- if (typeof block !== 'function') {
- throw new TypeError('"block" argument must be a function');
- }
- if (typeof expected === 'string') {
- message = expected;
- expected = null;
- }
- actual = _tryBlock(block);
- message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
- (message ? ' ' + message : '.');
- if (shouldThrow && !actual) {
- fail(actual, expected, 'Missing expected exception' + message);
- }
- var userProvidedMessage = typeof message === 'string';
- var isUnwantedException = !shouldThrow && util.isError(actual);
- var isUnexpectedException = !shouldThrow && actual && !expected;
- if ((isUnwantedException &&
- userProvidedMessage &&
- expectedException(actual, expected)) ||
- isUnexpectedException) {
- fail(actual, expected, 'Got unwanted exception' + message);
- }
- if ((shouldThrow && actual && expected &&
- !expectedException(actual, expected)) || (!shouldThrow && actual)) {
- throw actual;
- }
- }
- // 11. Expected to throw an error:
- // assert.throws(block, Error_opt, message_opt);
- assert.throws = function(block, /*optional*/error, /*optional*/message) {
- _throws(true, block, error, message);
- };
- // EXTENSION! This is annoying to write outside this module.
- assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
- _throws(false, block, error, message);
- };
- assert.ifError = function(err) { if (err) throw err; };
- // Expose a strict only variant of assert
- function strict(value, message) {
- if (!value) fail(value, true, message, '==', strict);
- }
- assert.strict = objectAssign(strict, assert, {
- equal: assert.strictEqual,
- deepEqual: assert.deepStrictEqual,
- notEqual: assert.notStrictEqual,
- notDeepEqual: assert.notDeepStrictEqual
- });
- assert.strict.strict = assert.strict;
- var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- if (hasOwn.call(obj, key)) keys.push(key);
- }
- return keys;
- };
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"object-assign":263,"util/":27}],25:[function(require,module,exports){
- if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- };
- } else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
- }
- },{}],26:[function(require,module,exports){
- module.exports = function isBuffer(arg) {
- return arg && typeof arg === 'object'
- && typeof arg.copy === 'function'
- && typeof arg.fill === 'function'
- && typeof arg.readUInt8 === 'function';
- }
- },{}],27:[function(require,module,exports){
- (function (process,global){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- var formatRegExp = /%[sdj%]/g;
- exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
- };
- // Mark that a method should not be used.
- // Returns a modified function which warns once by default.
- // If --no-deprecation is set, then it is a no-op.
- exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
- if (process.noDeprecation === true) {
- return fn;
- }
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
- return deprecated;
- };
- var debugs = {};
- var debugEnviron;
- exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
- }
- return debugs[set];
- };
- /**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
- /* legacy: obj, showHidden, depth, colors*/
- function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
- }
- exports.inspect = inspect;
- // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
- inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
- };
- // Don't use 'blue' not visible on cmd.exe
- inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
- };
- function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
- }
- function stylizeNoColor(str, styleType) {
- return str;
- }
- function arrayToHash(array) {
- var hash = {};
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
- return hash;
- }
- function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
- // IE doesn't make error fields non-enumerable
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
- if (isError(value)
- && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
- return formatError(value);
- }
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
- var base = '', array = false, braces = ['{', '}'];
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
- ctx.seen.push(value);
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
- ctx.seen.pop();
- return reduceToSingleString(output, base, braces);
- }
- function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value))
- return ctx.stylize('' + value, 'number');
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
- }
- function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
- }
- function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
- }
- function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
- return name + ': ' + str;
- }
- function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
- }
- // NOTE: These type checking functions intentionally don't use `instanceof`
- // because it is fragile and can be easily faked with `Object.create()`.
- function isArray(ar) {
- return Array.isArray(ar);
- }
- exports.isArray = isArray;
- function isBoolean(arg) {
- return typeof arg === 'boolean';
- }
- exports.isBoolean = isBoolean;
- function isNull(arg) {
- return arg === null;
- }
- exports.isNull = isNull;
- function isNullOrUndefined(arg) {
- return arg == null;
- }
- exports.isNullOrUndefined = isNullOrUndefined;
- function isNumber(arg) {
- return typeof arg === 'number';
- }
- exports.isNumber = isNumber;
- function isString(arg) {
- return typeof arg === 'string';
- }
- exports.isString = isString;
- function isSymbol(arg) {
- return typeof arg === 'symbol';
- }
- exports.isSymbol = isSymbol;
- function isUndefined(arg) {
- return arg === void 0;
- }
- exports.isUndefined = isUndefined;
- function isRegExp(re) {
- return isObject(re) && objectToString(re) === '[object RegExp]';
- }
- exports.isRegExp = isRegExp;
- function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
- }
- exports.isObject = isObject;
- function isDate(d) {
- return isObject(d) && objectToString(d) === '[object Date]';
- }
- exports.isDate = isDate;
- function isError(e) {
- return isObject(e) &&
- (objectToString(e) === '[object Error]' || e instanceof Error);
- }
- exports.isError = isError;
- function isFunction(arg) {
- return typeof arg === 'function';
- }
- exports.isFunction = isFunction;
- function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
- }
- exports.isPrimitive = isPrimitive;
- exports.isBuffer = require('./support/isBuffer');
- function objectToString(o) {
- return Object.prototype.toString.call(o);
- }
- function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
- }
- var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
- // 26 Feb 16:19:34
- function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
- }
- // log is just a thin wrapper to console.log that prepends a timestamp
- exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
- };
- /**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
- exports.inherits = require('inherits');
- exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
- };
- function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./support/isBuffer":26,"_process":312,"inherits":25}],28:[function(require,module,exports){
- 'use strict'
- exports.byteLength = byteLength
- exports.toByteArray = toByteArray
- exports.fromByteArray = fromByteArray
- var lookup = []
- var revLookup = []
- var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
- var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
- for (var i = 0, len = code.length; i < len; ++i) {
- lookup[i] = code[i]
- revLookup[code.charCodeAt(i)] = i
- }
- // Support decoding URL-safe base64 strings, as Node.js does.
- // See: https://en.wikipedia.org/wiki/Base64#URL_applications
- revLookup['-'.charCodeAt(0)] = 62
- revLookup['_'.charCodeAt(0)] = 63
- function getLens (b64) {
- var len = b64.length
- if (len % 4 > 0) {
- throw new Error('Invalid string. Length must be a multiple of 4')
- }
- // Trim off extra bytes after placeholder bytes are found
- // See: https://github.com/beatgammit/base64-js/issues/42
- var validLen = b64.indexOf('=')
- if (validLen === -1) validLen = len
- var placeHoldersLen = validLen === len
- ? 0
- : 4 - (validLen % 4)
- return [validLen, placeHoldersLen]
- }
- // base64 is 4/3 + up to two characters of the original data
- function byteLength (b64) {
- var lens = getLens(b64)
- var validLen = lens[0]
- var placeHoldersLen = lens[1]
- return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
- }
- function _byteLength (b64, validLen, placeHoldersLen) {
- return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
- }
- function toByteArray (b64) {
- var tmp
- var lens = getLens(b64)
- var validLen = lens[0]
- var placeHoldersLen = lens[1]
- var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
- var curByte = 0
- // if there are placeholders, only get up to the last complete 4 chars
- var len = placeHoldersLen > 0
- ? validLen - 4
- : validLen
- var i
- for (i = 0; i < len; i += 4) {
- tmp =
- (revLookup[b64.charCodeAt(i)] << 18) |
- (revLookup[b64.charCodeAt(i + 1)] << 12) |
- (revLookup[b64.charCodeAt(i + 2)] << 6) |
- revLookup[b64.charCodeAt(i + 3)]
- arr[curByte++] = (tmp >> 16) & 0xFF
- arr[curByte++] = (tmp >> 8) & 0xFF
- arr[curByte++] = tmp & 0xFF
- }
- if (placeHoldersLen === 2) {
- tmp =
- (revLookup[b64.charCodeAt(i)] << 2) |
- (revLookup[b64.charCodeAt(i + 1)] >> 4)
- arr[curByte++] = tmp & 0xFF
- }
- if (placeHoldersLen === 1) {
- tmp =
- (revLookup[b64.charCodeAt(i)] << 10) |
- (revLookup[b64.charCodeAt(i + 1)] << 4) |
- (revLookup[b64.charCodeAt(i + 2)] >> 2)
- arr[curByte++] = (tmp >> 8) & 0xFF
- arr[curByte++] = tmp & 0xFF
- }
- return arr
- }
- function tripletToBase64 (num) {
- return lookup[num >> 18 & 0x3F] +
- lookup[num >> 12 & 0x3F] +
- lookup[num >> 6 & 0x3F] +
- lookup[num & 0x3F]
- }
- function encodeChunk (uint8, start, end) {
- var tmp
- var output = []
- for (var i = start; i < end; i += 3) {
- tmp =
- ((uint8[i] << 16) & 0xFF0000) +
- ((uint8[i + 1] << 8) & 0xFF00) +
- (uint8[i + 2] & 0xFF)
- output.push(tripletToBase64(tmp))
- }
- return output.join('')
- }
- function fromByteArray (uint8) {
- var tmp
- var len = uint8.length
- var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
- var parts = []
- var maxChunkLength = 16383 // must be multiple of 3
- // go through the array every three bytes, we'll deal with trailing stuff later
- for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
- parts.push(encodeChunk(
- uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
- ))
- }
- // pad the end with zeros, but make sure to not forget the extra bytes
- if (extraBytes === 1) {
- tmp = uint8[len - 1]
- parts.push(
- lookup[tmp >> 2] +
- lookup[(tmp << 4) & 0x3F] +
- '=='
- )
- } else if (extraBytes === 2) {
- tmp = (uint8[len - 2] << 8) + uint8[len - 1]
- parts.push(
- lookup[tmp >> 10] +
- lookup[(tmp >> 4) & 0x3F] +
- lookup[(tmp << 2) & 0x3F] +
- '='
- )
- }
- return parts.join('')
- }
- },{}],29:[function(require,module,exports){
- /**
- * @author shaozilee
- *
- * support 1bit 4bit 8bit 24bit decode
- * encode with 24bit
- *
- */
- var encode = require('./lib/encoder'),
- decode = require('./lib/decoder');
- module.exports = {
- encode: encode,
- decode: decode
- };
- },{"./lib/decoder":30,"./lib/encoder":31}],30:[function(require,module,exports){
- (function (Buffer){
- /**
- * @author shaozilee
- *
- * Bmp format decoder,support 1bit 4bit 8bit 24bit bmp
- *
- */
- function BmpDecoder(buffer,is_with_alpha) {
- this.pos = 0;
- this.buffer = buffer;
- this.is_with_alpha = !!is_with_alpha;
- this.bottom_up = true;
- this.flag = this.buffer.toString("utf-8", 0, this.pos += 2);
- if (this.flag != "BM") throw new Error("Invalid BMP File");
- this.parseHeader();
- this.parseRGBA();
- }
- BmpDecoder.prototype.parseHeader = function() {
- this.fileSize = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- this.reserved = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- this.offset = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- this.headerSize = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- this.width = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- this.height = this.buffer.readInt32LE(this.pos);
- this.pos += 4;
- this.planes = this.buffer.readUInt16LE(this.pos);
- this.pos += 2;
- this.bitPP = this.buffer.readUInt16LE(this.pos);
- this.pos += 2;
- this.compress = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- this.rawSize = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- this.hr = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- this.vr = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- this.colors = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- this.importantColors = this.buffer.readUInt32LE(this.pos);
- this.pos += 4;
- if(this.bitPP === 16 && this.is_with_alpha){
- this.bitPP = 15
- }
- if (this.bitPP < 15) {
- var len = this.colors === 0 ? 1 << this.bitPP : this.colors;
- this.palette = new Array(len);
- for (var i = 0; i < len; i++) {
- var blue = this.buffer.readUInt8(this.pos++);
- var green = this.buffer.readUInt8(this.pos++);
- var red = this.buffer.readUInt8(this.pos++);
- var quad = this.buffer.readUInt8(this.pos++);
- this.palette[i] = {
- red: red,
- green: green,
- blue: blue,
- quad: quad
- };
- }
- }
- if(this.height < 0) {
- this.height *= -1;
- this.bottom_up = false;
- }
- }
- BmpDecoder.prototype.parseRGBA = function() {
- var bitn = "bit" + this.bitPP;
- var len = this.width * this.height * 4;
- this.data = new Buffer(len);
- this[bitn]();
- };
- BmpDecoder.prototype.bit1 = function() {
- var xlen = Math.ceil(this.width / 8);
- var mode = xlen%4;
- var y = this.height >= 0 ? this.height - 1 : -this.height
- for (var y = this.height - 1; y >= 0; y--) {
- var line = this.bottom_up ? y : this.height - 1 - y
- for (var x = 0; x < xlen; x++) {
- var b = this.buffer.readUInt8(this.pos++);
- var location = line * this.width * 4 + x*8*4;
- for (var i = 0; i < 8; i++) {
- if(x*8+i<this.width){
- var rgb = this.palette[((b>>(7-i))&0x1)];
- this.data[location+i*4] = 0;
- this.data[location+i*4 + 1] = rgb.blue;
- this.data[location+i*4 + 2] = rgb.green;
- this.data[location+i*4 + 3] = rgb.red;
- }else{
- break;
- }
- }
- }
- if (mode != 0){
- this.pos+=(4 - mode);
- }
- }
- };
- BmpDecoder.prototype.bit4 = function() {
- //RLE-4
- if(this.compress == 2){
- this.data.fill(0xff);
- var location = 0;
- var lines = this.bottom_up?this.height-1:0;
- var low_nibble = false;//for all count of pixel
- while(location<this.data.length){
- var a = this.buffer.readUInt8(this.pos++);
- var b = this.buffer.readUInt8(this.pos++);
- //absolute mode
- if(a == 0){
- if(b == 0){//line end
- if(this.bottom_up){
- lines--;
- }else{
- lines++;
- }
- location = lines*this.width*4;
- low_nibble = false;
- continue;
- }else if(b == 1){//image end
- break;
- }else if(b ==2){
- //offset x,y
- var x = this.buffer.readUInt8(this.pos++);
- var y = this.buffer.readUInt8(this.pos++);
- if(this.bottom_up){
- lines-=y;
- }else{
- lines+=y;
- }
- location +=(y*this.width*4+x*4);
- }else{
- var c = this.buffer.readUInt8(this.pos++);
- for(var i=0;i<b;i++){
- if (low_nibble) {
- setPixelData.call(this, (c & 0x0f));
- } else {
- setPixelData.call(this, (c & 0xf0)>>4);
- }
- if ((i & 1) && (i+1 < b)){
- c = this.buffer.readUInt8(this.pos++);
- }
- low_nibble = !low_nibble;
- }
- if ((((b+1) >> 1) & 1 ) == 1){
- this.pos++
- }
- }
- }else{//encoded mode
- for (var i = 0; i < a; i++) {
- if (low_nibble) {
- setPixelData.call(this, (b & 0x0f));
- } else {
- setPixelData.call(this, (b & 0xf0)>>4);
- }
- low_nibble = !low_nibble;
- }
- }
- }
- function setPixelData(rgbIndex){
- var rgb = this.palette[rgbIndex];
- this.data[location] = 0;
- this.data[location + 1] = rgb.blue;
- this.data[location + 2] = rgb.green;
- this.data[location + 3] = rgb.red;
- location+=4;
- }
- }else{
- var xlen = Math.ceil(this.width/2);
- var mode = xlen%4;
- for (var y = this.height - 1; y >= 0; y--) {
- var line = this.bottom_up ? y : this.height - 1 - y
- for (var x = 0; x < xlen; x++) {
- var b = this.buffer.readUInt8(this.pos++);
- var location = line * this.width * 4 + x*2*4;
- var before = b>>4;
- var after = b&0x0F;
- var rgb = this.palette[before];
- this.data[location] = 0;
- this.data[location + 1] = rgb.blue;
- this.data[location + 2] = rgb.green;
- this.data[location + 3] = rgb.red;
- if(x*2+1>=this.width)break;
- rgb = this.palette[after];
- this.data[location+4] = 0;
- this.data[location+4 + 1] = rgb.blue;
- this.data[location+4 + 2] = rgb.green;
- this.data[location+4 + 3] = rgb.red;
- }
- if (mode != 0){
- this.pos+=(4 - mode);
- }
- }
- }
- };
- BmpDecoder.prototype.bit8 = function() {
- //RLE-8
- if(this.compress == 1){
- this.data.fill(0xff);
- var location = 0;
- var lines = this.bottom_up?this.height-1:0;
- while(location<this.data.length){
- var a = this.buffer.readUInt8(this.pos++);
- var b = this.buffer.readUInt8(this.pos++);
- //absolute mode
- if(a == 0){
- if(b == 0){//line end
- if(this.bottom_up){
- lines--;
- }else{
- lines++;
- }
- location = lines*this.width*4;
- continue;
- }else if(b == 1){//image end
- break;
- }else if(b ==2){
- //offset x,y
- var x = this.buffer.readUInt8(this.pos++);
- var y = this.buffer.readUInt8(this.pos++);
- if(this.bottom_up){
- lines-=y;
- }else{
- lines+=y;
- }
- location +=(y*this.width*4+x*4);
- }else{
- for(var i=0;i<b;i++){
- var c = this.buffer.readUInt8(this.pos++);
- setPixelData.call(this, c);
- }
- if(b&1 == 1){
- this.pos++;
- }
- }
- }else{//encoded mode
- for (var i = 0; i < a; i++) {
- setPixelData.call(this, b);
- }
- }
- }
- function setPixelData(rgbIndex){
- var rgb = this.palette[rgbIndex];
- this.data[location] = 0;
- this.data[location + 1] = rgb.blue;
- this.data[location + 2] = rgb.green;
- this.data[location + 3] = rgb.red;
- location+=4;
- }
- }else {
- var mode = this.width % 4;
- for (var y = this.height - 1; y >= 0; y--) {
- var line = this.bottom_up ? y : this.height - 1 - y
- for (var x = 0; x < this.width; x++) {
- var b = this.buffer.readUInt8(this.pos++);
- var location = line * this.width * 4 + x * 4;
- if (b < this.palette.length) {
- var rgb = this.palette[b];
- this.data[location] = 0;
- this.data[location + 1] = rgb.blue;
- this.data[location + 2] = rgb.green;
- this.data[location + 3] = rgb.red;
- } else {
- this.data[location] = 0;
- this.data[location + 1] = 0xFF;
- this.data[location + 2] = 0xFF;
- this.data[location + 3] = 0xFF;
- }
- }
- if (mode != 0) {
- this.pos += (4 - mode);
- }
- }
- }
- };
- BmpDecoder.prototype.bit15 = function() {
- var dif_w =this.width % 3;
- var _11111 = parseInt("11111", 2),_1_5 = _11111;
- for (var y = this.height - 1; y >= 0; y--) {
- var line = this.bottom_up ? y : this.height - 1 - y
- for (var x = 0; x < this.width; x++) {
- var B = this.buffer.readUInt16LE(this.pos);
- this.pos+=2;
- var blue = (B & _1_5) / _1_5 * 255 | 0;
- var green = (B >> 5 & _1_5 ) / _1_5 * 255 | 0;
- var red = (B >> 10 & _1_5) / _1_5 * 255 | 0;
- var alpha = (B>>15)?0xFF:0x00;
- var location = line * this.width * 4 + x * 4;
- this.data[location] = alpha;
- this.data[location + 1] = blue;
- this.data[location + 2] = green;
- this.data[location + 3] = red;
- }
- //skip extra bytes
- this.pos += dif_w;
- }
- };
- BmpDecoder.prototype.bit16 = function() {
- var dif_w =(this.width % 2)*2;
- //default xrgb555
- this.maskRed = 0x7C00;
- this.maskGreen = 0x3E0;
- this.maskBlue =0x1F;
- this.mask0 = 0;
- if(this.compress == 3){
- this.maskRed = this.buffer.readUInt32LE(this.pos);
- this.pos+=4;
- this.maskGreen = this.buffer.readUInt32LE(this.pos);
- this.pos+=4;
- this.maskBlue = this.buffer.readUInt32LE(this.pos);
- this.pos+=4;
- this.mask0 = this.buffer.readUInt32LE(this.pos);
- this.pos+=4;
- }
- var ns=[0,0,0];
- for (var i=0;i<16;i++){
- if ((this.maskRed>>i)&0x01) ns[0]++;
- if ((this.maskGreen>>i)&0x01) ns[1]++;
- if ((this.maskBlue>>i)&0x01) ns[2]++;
- }
- ns[1]+=ns[0]; ns[2]+=ns[1]; ns[0]=8-ns[0]; ns[1]-=8; ns[2]-=8;
- for (var y = this.height - 1; y >= 0; y--) {
- var line = this.bottom_up ? y : this.height - 1 - y;
- for (var x = 0; x < this.width; x++) {
- var B = this.buffer.readUInt16LE(this.pos);
- this.pos+=2;
- var blue = (B&this.maskBlue)<<ns[0];
- var green = (B&this.maskGreen)>>ns[1];
- var red = (B&this.maskRed)>>ns[2];
- var location = line * this.width * 4 + x * 4;
- this.data[location] = 0;
- this.data[location + 1] = blue;
- this.data[location + 2] = green;
- this.data[location + 3] = red;
- }
- //skip extra bytes
- this.pos += dif_w;
- }
- };
- BmpDecoder.prototype.bit24 = function() {
- for (var y = this.height - 1; y >= 0; y--) {
- var line = this.bottom_up ? y : this.height - 1 - y
- for (var x = 0; x < this.width; x++) {
- //Little Endian rgb
- var blue = this.buffer.readUInt8(this.pos++);
- var green = this.buffer.readUInt8(this.pos++);
- var red = this.buffer.readUInt8(this.pos++);
- var location = line * this.width * 4 + x * 4;
- this.data[location] = 0;
- this.data[location + 1] = blue;
- this.data[location + 2] = green;
- this.data[location + 3] = red;
- }
- //skip extra bytes
- this.pos += (this.width % 4);
- }
- };
- /**
- * add 32bit decode func
- * @author soubok
- */
- BmpDecoder.prototype.bit32 = function() {
- //BI_BITFIELDS
- if(this.compress == 3){
- this.maskRed = this.buffer.readUInt32LE(this.pos);
- this.pos+=4;
- this.maskGreen = this.buffer.readUInt32LE(this.pos);
- this.pos+=4;
- this.maskBlue = this.buffer.readUInt32LE(this.pos);
- this.pos+=4;
- this.mask0 = this.buffer.readUInt32LE(this.pos);
- this.pos+=4;
- for (var y = this.height - 1; y >= 0; y--) {
- var line = this.bottom_up ? y : this.height - 1 - y;
- for (var x = 0; x < this.width; x++) {
- //Little Endian rgba
- var alpha = this.buffer.readUInt8(this.pos++);
- var blue = this.buffer.readUInt8(this.pos++);
- var green = this.buffer.readUInt8(this.pos++);
- var red = this.buffer.readUInt8(this.pos++);
- var location = line * this.width * 4 + x * 4;
- this.data[location] = alpha;
- this.data[location + 1] = blue;
- this.data[location + 2] = green;
- this.data[location + 3] = red;
- }
- }
- }else{
- for (var y = this.height - 1; y >= 0; y--) {
- var line = this.bottom_up ? y : this.height - 1 - y;
- for (var x = 0; x < this.width; x++) {
- //Little Endian argb
- var blue = this.buffer.readUInt8(this.pos++);
- var green = this.buffer.readUInt8(this.pos++);
- var red = this.buffer.readUInt8(this.pos++);
- var alpha = this.buffer.readUInt8(this.pos++);
- var location = line * this.width * 4 + x * 4;
- this.data[location] = alpha;
- this.data[location + 1] = blue;
- this.data[location + 2] = green;
- this.data[location + 3] = red;
- }
- }
- }
- };
- BmpDecoder.prototype.getData = function() {
- return this.data;
- };
- module.exports = function(bmpData) {
- var decoder = new BmpDecoder(bmpData);
- return decoder;
- };
- }).call(this,require("buffer").Buffer)
- },{"buffer":47}],31:[function(require,module,exports){
- (function (Buffer){
- /**
- * @author shaozilee
- *
- * BMP format encoder,encode 24bit BMP
- * Not support quality compression
- *
- */
- function BmpEncoder(imgData){
- this.buffer = imgData.data;
- this.width = imgData.width;
- this.height = imgData.height;
- this.extraBytes = this.width%4;
- this.rgbSize = this.height*(3*this.width+this.extraBytes);
- this.headerInfoSize = 40;
- this.data = [];
- /******************header***********************/
- this.flag = "BM";
- this.reserved = 0;
- this.offset = 54;
- this.fileSize = this.rgbSize+this.offset;
- this.planes = 1;
- this.bitPP = 24;
- this.compress = 0;
- this.hr = 0;
- this.vr = 0;
- this.colors = 0;
- this.importantColors = 0;
- }
- BmpEncoder.prototype.encode = function() {
- var tempBuffer = new Buffer(this.offset+this.rgbSize);
- this.pos = 0;
- tempBuffer.write(this.flag,this.pos,2);this.pos+=2;
- tempBuffer.writeUInt32LE(this.fileSize,this.pos);this.pos+=4;
- tempBuffer.writeUInt32LE(this.reserved,this.pos);this.pos+=4;
- tempBuffer.writeUInt32LE(this.offset,this.pos);this.pos+=4;
- tempBuffer.writeUInt32LE(this.headerInfoSize,this.pos);this.pos+=4;
- tempBuffer.writeUInt32LE(this.width,this.pos);this.pos+=4;
- tempBuffer.writeInt32LE(-this.height,this.pos);this.pos+=4;
- tempBuffer.writeUInt16LE(this.planes,this.pos);this.pos+=2;
- tempBuffer.writeUInt16LE(this.bitPP,this.pos);this.pos+=2;
- tempBuffer.writeUInt32LE(this.compress,this.pos);this.pos+=4;
- tempBuffer.writeUInt32LE(this.rgbSize,this.pos);this.pos+=4;
- tempBuffer.writeUInt32LE(this.hr,this.pos);this.pos+=4;
- tempBuffer.writeUInt32LE(this.vr,this.pos);this.pos+=4;
- tempBuffer.writeUInt32LE(this.colors,this.pos);this.pos+=4;
- tempBuffer.writeUInt32LE(this.importantColors,this.pos);this.pos+=4;
- var i=0;
- var rowBytes = 3*this.width+this.extraBytes;
- for (var y = 0; y <this.height; y++){
- for (var x = 0; x < this.width; x++){
- var p = this.pos+y*rowBytes+x*3;
- i++;//a
- tempBuffer[p]= this.buffer[i++];//b
- tempBuffer[p+1] = this.buffer[i++];//g
- tempBuffer[p+2] = this.buffer[i++];//r
- }
- if(this.extraBytes>0){
- var fillOffset = this.pos+y*rowBytes+this.width*3;
- tempBuffer.fill(0,fillOffset,fillOffset+this.extraBytes);
- }
- }
- return tempBuffer;
- };
- module.exports = function(imgData, quality) {
- if (typeof quality === 'undefined') quality = 100;
- var encoder = new BmpEncoder(imgData);
- var data = encoder.encode();
- return {
- data: data,
- width: imgData.width,
- height: imgData.height
- };
- };
- }).call(this,require("buffer").Buffer)
- },{"buffer":47}],32:[function(require,module,exports){
- },{}],33:[function(require,module,exports){
- (function (process,Buffer){
- 'use strict';
- /* eslint camelcase: "off" */
- var assert = require('assert');
- var Zstream = require('pako/lib/zlib/zstream');
- var zlib_deflate = require('pako/lib/zlib/deflate.js');
- var zlib_inflate = require('pako/lib/zlib/inflate.js');
- var constants = require('pako/lib/zlib/constants');
- for (var key in constants) {
- exports[key] = constants[key];
- }
- // zlib modes
- exports.NONE = 0;
- exports.DEFLATE = 1;
- exports.INFLATE = 2;
- exports.GZIP = 3;
- exports.GUNZIP = 4;
- exports.DEFLATERAW = 5;
- exports.INFLATERAW = 6;
- exports.UNZIP = 7;
- var GZIP_HEADER_ID1 = 0x1f;
- var GZIP_HEADER_ID2 = 0x8b;
- /**
- * Emulate Node's zlib C++ layer for use by the JS layer in index.js
- */
- function Zlib(mode) {
- if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
- throw new TypeError('Bad argument');
- }
- this.dictionary = null;
- this.err = 0;
- this.flush = 0;
- this.init_done = false;
- this.level = 0;
- this.memLevel = 0;
- this.mode = mode;
- this.strategy = 0;
- this.windowBits = 0;
- this.write_in_progress = false;
- this.pending_close = false;
- this.gzip_id_bytes_read = 0;
- }
- Zlib.prototype.close = function () {
- if (this.write_in_progress) {
- this.pending_close = true;
- return;
- }
- this.pending_close = false;
- assert(this.init_done, 'close before init');
- assert(this.mode <= exports.UNZIP);
- if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
- zlib_deflate.deflateEnd(this.strm);
- } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
- zlib_inflate.inflateEnd(this.strm);
- }
- this.mode = exports.NONE;
- this.dictionary = null;
- };
- Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
- return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
- };
- Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
- return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
- };
- Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
- assert.equal(arguments.length, 8);
- assert(this.init_done, 'write before init');
- assert(this.mode !== exports.NONE, 'already finalized');
- assert.equal(false, this.write_in_progress, 'write already in progress');
- assert.equal(false, this.pending_close, 'close is pending');
- this.write_in_progress = true;
- assert.equal(false, flush === undefined, 'must provide flush value');
- this.write_in_progress = true;
- if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {
- throw new Error('Invalid flush value');
- }
- if (input == null) {
- input = Buffer.alloc(0);
- in_len = 0;
- in_off = 0;
- }
- this.strm.avail_in = in_len;
- this.strm.input = input;
- this.strm.next_in = in_off;
- this.strm.avail_out = out_len;
- this.strm.output = out;
- this.strm.next_out = out_off;
- this.flush = flush;
- if (!async) {
- // sync version
- this._process();
- if (this._checkError()) {
- return this._afterSync();
- }
- return;
- }
- // async version
- var self = this;
- process.nextTick(function () {
- self._process();
- self._after();
- });
- return this;
- };
- Zlib.prototype._afterSync = function () {
- var avail_out = this.strm.avail_out;
- var avail_in = this.strm.avail_in;
- this.write_in_progress = false;
- return [avail_in, avail_out];
- };
- Zlib.prototype._process = function () {
- var next_expected_header_byte = null;
- // If the avail_out is left at 0, then it means that it ran out
- // of room. If there was avail_out left over, then it means
- // that all of the input was consumed.
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.GZIP:
- case exports.DEFLATERAW:
- this.err = zlib_deflate.deflate(this.strm, this.flush);
- break;
- case exports.UNZIP:
- if (this.strm.avail_in > 0) {
- next_expected_header_byte = this.strm.next_in;
- }
- switch (this.gzip_id_bytes_read) {
- case 0:
- if (next_expected_header_byte === null) {
- break;
- }
- if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
- this.gzip_id_bytes_read = 1;
- next_expected_header_byte++;
- if (this.strm.avail_in === 1) {
- // The only available byte was already read.
- break;
- }
- } else {
- this.mode = exports.INFLATE;
- break;
- }
- // fallthrough
- case 1:
- if (next_expected_header_byte === null) {
- break;
- }
- if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
- this.gzip_id_bytes_read = 2;
- this.mode = exports.GUNZIP;
- } else {
- // There is no actual difference between INFLATE and INFLATERAW
- // (after initialization).
- this.mode = exports.INFLATE;
- }
- break;
- default:
- throw new Error('invalid number of gzip magic number bytes read');
- }
- // fallthrough
- case exports.INFLATE:
- case exports.GUNZIP:
- case exports.INFLATERAW:
- this.err = zlib_inflate.inflate(this.strm, this.flush
- // If data was encoded with dictionary
- );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
- // Load it
- this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
- if (this.err === exports.Z_OK) {
- // And try to decode again
- this.err = zlib_inflate.inflate(this.strm, this.flush);
- } else if (this.err === exports.Z_DATA_ERROR) {
- // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
- // Make it possible for After() to tell a bad dictionary from bad
- // input.
- this.err = exports.Z_NEED_DICT;
- }
- }
- while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
- // Bytes remain in input buffer. Perhaps this is another compressed
- // member in the same archive, or just trailing garbage.
- // Trailing zero bytes are okay, though, since they are frequently
- // used for padding.
- this.reset();
- this.err = zlib_inflate.inflate(this.strm, this.flush);
- }
- break;
- default:
- throw new Error('Unknown mode ' + this.mode);
- }
- };
- Zlib.prototype._checkError = function () {
- // Acceptable error states depend on the type of zlib stream.
- switch (this.err) {
- case exports.Z_OK:
- case exports.Z_BUF_ERROR:
- if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
- this._error('unexpected end of file');
- return false;
- }
- break;
- case exports.Z_STREAM_END:
- // normal statuses, not fatal
- break;
- case exports.Z_NEED_DICT:
- if (this.dictionary == null) {
- this._error('Missing dictionary');
- } else {
- this._error('Bad dictionary');
- }
- return false;
- default:
- // something else.
- this._error('Zlib error');
- return false;
- }
- return true;
- };
- Zlib.prototype._after = function () {
- if (!this._checkError()) {
- return;
- }
- var avail_out = this.strm.avail_out;
- var avail_in = this.strm.avail_in;
- this.write_in_progress = false;
- // call the write() cb
- this.callback(avail_in, avail_out);
- if (this.pending_close) {
- this.close();
- }
- };
- Zlib.prototype._error = function (message) {
- if (this.strm.msg) {
- message = this.strm.msg;
- }
- this.onerror(message, this.err
- // no hope of rescue.
- );this.write_in_progress = false;
- if (this.pending_close) {
- this.close();
- }
- };
- Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
- assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
- assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
- assert(level >= -1 && level <= 9, 'invalid compression level');
- assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
- assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');
- this._init(level, windowBits, memLevel, strategy, dictionary);
- this._setDictionary();
- };
- Zlib.prototype.params = function () {
- throw new Error('deflateParams Not supported');
- };
- Zlib.prototype.reset = function () {
- this._reset();
- this._setDictionary();
- };
- Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
- this.level = level;
- this.windowBits = windowBits;
- this.memLevel = memLevel;
- this.strategy = strategy;
- this.flush = exports.Z_NO_FLUSH;
- this.err = exports.Z_OK;
- if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
- this.windowBits += 16;
- }
- if (this.mode === exports.UNZIP) {
- this.windowBits += 32;
- }
- if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
- this.windowBits = -1 * this.windowBits;
- }
- this.strm = new Zstream();
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.GZIP:
- case exports.DEFLATERAW:
- this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
- break;
- case exports.INFLATE:
- case exports.GUNZIP:
- case exports.INFLATERAW:
- case exports.UNZIP:
- this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
- break;
- default:
- throw new Error('Unknown mode ' + this.mode);
- }
- if (this.err !== exports.Z_OK) {
- this._error('Init error');
- }
- this.dictionary = dictionary;
- this.write_in_progress = false;
- this.init_done = true;
- };
- Zlib.prototype._setDictionary = function () {
- if (this.dictionary == null) {
- return;
- }
- this.err = exports.Z_OK;
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.DEFLATERAW:
- this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
- break;
- default:
- break;
- }
- if (this.err !== exports.Z_OK) {
- this._error('Failed to set dictionary');
- }
- };
- Zlib.prototype._reset = function () {
- this.err = exports.Z_OK;
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.DEFLATERAW:
- case exports.GZIP:
- this.err = zlib_deflate.deflateReset(this.strm);
- break;
- case exports.INFLATE:
- case exports.INFLATERAW:
- case exports.GUNZIP:
- this.err = zlib_inflate.inflateReset(this.strm);
- break;
- default:
- break;
- }
- if (this.err !== exports.Z_OK) {
- this._error('Failed to reset stream');
- }
- };
- exports.Zlib = Zlib;
- }).call(this,require('_process'),require("buffer").Buffer)
- },{"_process":312,"assert":24,"buffer":47,"pako/lib/zlib/constants":37,"pako/lib/zlib/deflate.js":39,"pako/lib/zlib/inflate.js":41,"pako/lib/zlib/zstream":45}],34:[function(require,module,exports){
- (function (process){
- 'use strict';
- var Buffer = require('buffer').Buffer;
- var Transform = require('stream').Transform;
- var binding = require('./binding');
- var util = require('util');
- var assert = require('assert').ok;
- var kMaxLength = require('buffer').kMaxLength;
- var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
- // zlib doesn't provide these, so kludge them in following the same
- // const naming scheme zlib uses.
- binding.Z_MIN_WINDOWBITS = 8;
- binding.Z_MAX_WINDOWBITS = 15;
- binding.Z_DEFAULT_WINDOWBITS = 15;
- // fewer than 64 bytes per chunk is stupid.
- // technically it could work with as few as 8, but even 64 bytes
- // is absurdly low. Usually a MB or more is best.
- binding.Z_MIN_CHUNK = 64;
- binding.Z_MAX_CHUNK = Infinity;
- binding.Z_DEFAULT_CHUNK = 16 * 1024;
- binding.Z_MIN_MEMLEVEL = 1;
- binding.Z_MAX_MEMLEVEL = 9;
- binding.Z_DEFAULT_MEMLEVEL = 8;
- binding.Z_MIN_LEVEL = -1;
- binding.Z_MAX_LEVEL = 9;
- binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
- // expose all the zlib constants
- var bkeys = Object.keys(binding);
- for (var bk = 0; bk < bkeys.length; bk++) {
- var bkey = bkeys[bk];
- if (bkey.match(/^Z/)) {
- Object.defineProperty(exports, bkey, {
- enumerable: true, value: binding[bkey], writable: false
- });
- }
- }
- // translation table for return codes.
- var codes = {
- Z_OK: binding.Z_OK,
- Z_STREAM_END: binding.Z_STREAM_END,
- Z_NEED_DICT: binding.Z_NEED_DICT,
- Z_ERRNO: binding.Z_ERRNO,
- Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
- Z_DATA_ERROR: binding.Z_DATA_ERROR,
- Z_MEM_ERROR: binding.Z_MEM_ERROR,
- Z_BUF_ERROR: binding.Z_BUF_ERROR,
- Z_VERSION_ERROR: binding.Z_VERSION_ERROR
- };
- var ckeys = Object.keys(codes);
- for (var ck = 0; ck < ckeys.length; ck++) {
- var ckey = ckeys[ck];
- codes[codes[ckey]] = ckey;
- }
- Object.defineProperty(exports, 'codes', {
- enumerable: true, value: Object.freeze(codes), writable: false
- });
- exports.Deflate = Deflate;
- exports.Inflate = Inflate;
- exports.Gzip = Gzip;
- exports.Gunzip = Gunzip;
- exports.DeflateRaw = DeflateRaw;
- exports.InflateRaw = InflateRaw;
- exports.Unzip = Unzip;
- exports.createDeflate = function (o) {
- return new Deflate(o);
- };
- exports.createInflate = function (o) {
- return new Inflate(o);
- };
- exports.createDeflateRaw = function (o) {
- return new DeflateRaw(o);
- };
- exports.createInflateRaw = function (o) {
- return new InflateRaw(o);
- };
- exports.createGzip = function (o) {
- return new Gzip(o);
- };
- exports.createGunzip = function (o) {
- return new Gunzip(o);
- };
- exports.createUnzip = function (o) {
- return new Unzip(o);
- };
- // Convenience methods.
- // compress/decompress a string or buffer in one step.
- exports.deflate = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Deflate(opts), buffer, callback);
- };
- exports.deflateSync = function (buffer, opts) {
- return zlibBufferSync(new Deflate(opts), buffer);
- };
- exports.gzip = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Gzip(opts), buffer, callback);
- };
- exports.gzipSync = function (buffer, opts) {
- return zlibBufferSync(new Gzip(opts), buffer);
- };
- exports.deflateRaw = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new DeflateRaw(opts), buffer, callback);
- };
- exports.deflateRawSync = function (buffer, opts) {
- return zlibBufferSync(new DeflateRaw(opts), buffer);
- };
- exports.unzip = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Unzip(opts), buffer, callback);
- };
- exports.unzipSync = function (buffer, opts) {
- return zlibBufferSync(new Unzip(opts), buffer);
- };
- exports.inflate = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Inflate(opts), buffer, callback);
- };
- exports.inflateSync = function (buffer, opts) {
- return zlibBufferSync(new Inflate(opts), buffer);
- };
- exports.gunzip = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Gunzip(opts), buffer, callback);
- };
- exports.gunzipSync = function (buffer, opts) {
- return zlibBufferSync(new Gunzip(opts), buffer);
- };
- exports.inflateRaw = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new InflateRaw(opts), buffer, callback);
- };
- exports.inflateRawSync = function (buffer, opts) {
- return zlibBufferSync(new InflateRaw(opts), buffer);
- };
- function zlibBuffer(engine, buffer, callback) {
- var buffers = [];
- var nread = 0;
- engine.on('error', onError);
- engine.on('end', onEnd);
- engine.end(buffer);
- flow();
- function flow() {
- var chunk;
- while (null !== (chunk = engine.read())) {
- buffers.push(chunk);
- nread += chunk.length;
- }
- engine.once('readable', flow);
- }
- function onError(err) {
- engine.removeListener('end', onEnd);
- engine.removeListener('readable', flow);
- callback(err);
- }
- function onEnd() {
- var buf;
- var err = null;
- if (nread >= kMaxLength) {
- err = new RangeError(kRangeErrorMessage);
- } else {
- buf = Buffer.concat(buffers, nread);
- }
- buffers = [];
- engine.close();
- callback(err, buf);
- }
- }
- function zlibBufferSync(engine, buffer) {
- if (typeof buffer === 'string') buffer = Buffer.from(buffer);
- if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
- var flushFlag = engine._finishFlushFlag;
- return engine._processChunk(buffer, flushFlag);
- }
- // generic zlib
- // minimal 2-byte header
- function Deflate(opts) {
- if (!(this instanceof Deflate)) return new Deflate(opts);
- Zlib.call(this, opts, binding.DEFLATE);
- }
- function Inflate(opts) {
- if (!(this instanceof Inflate)) return new Inflate(opts);
- Zlib.call(this, opts, binding.INFLATE);
- }
- // gzip - bigger header, same deflate compression
- function Gzip(opts) {
- if (!(this instanceof Gzip)) return new Gzip(opts);
- Zlib.call(this, opts, binding.GZIP);
- }
- function Gunzip(opts) {
- if (!(this instanceof Gunzip)) return new Gunzip(opts);
- Zlib.call(this, opts, binding.GUNZIP);
- }
- // raw - no header
- function DeflateRaw(opts) {
- if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
- Zlib.call(this, opts, binding.DEFLATERAW);
- }
- function InflateRaw(opts) {
- if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
- Zlib.call(this, opts, binding.INFLATERAW);
- }
- // auto-detect header.
- function Unzip(opts) {
- if (!(this instanceof Unzip)) return new Unzip(opts);
- Zlib.call(this, opts, binding.UNZIP);
- }
- function isValidFlushFlag(flag) {
- return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;
- }
- // the Zlib class they all inherit from
- // This thing manages the queue of requests, and returns
- // true or false if there is anything in the queue when
- // you call the .write() method.
- function Zlib(opts, mode) {
- var _this = this;
- this._opts = opts = opts || {};
- this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
- Transform.call(this, opts);
- if (opts.flush && !isValidFlushFlag(opts.flush)) {
- throw new Error('Invalid flush flag: ' + opts.flush);
- }
- if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
- throw new Error('Invalid flush flag: ' + opts.finishFlush);
- }
- this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
- this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
- if (opts.chunkSize) {
- if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
- throw new Error('Invalid chunk size: ' + opts.chunkSize);
- }
- }
- if (opts.windowBits) {
- if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
- throw new Error('Invalid windowBits: ' + opts.windowBits);
- }
- }
- if (opts.level) {
- if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
- throw new Error('Invalid compression level: ' + opts.level);
- }
- }
- if (opts.memLevel) {
- if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
- throw new Error('Invalid memLevel: ' + opts.memLevel);
- }
- }
- if (opts.strategy) {
- if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {
- throw new Error('Invalid strategy: ' + opts.strategy);
- }
- }
- if (opts.dictionary) {
- if (!Buffer.isBuffer(opts.dictionary)) {
- throw new Error('Invalid dictionary: it should be a Buffer instance');
- }
- }
- this._handle = new binding.Zlib(mode);
- var self = this;
- this._hadError = false;
- this._handle.onerror = function (message, errno) {
- // there is no way to cleanly recover.
- // continuing only obscures problems.
- _close(self);
- self._hadError = true;
- var error = new Error(message);
- error.errno = errno;
- error.code = exports.codes[errno];
- self.emit('error', error);
- };
- var level = exports.Z_DEFAULT_COMPRESSION;
- if (typeof opts.level === 'number') level = opts.level;
- var strategy = exports.Z_DEFAULT_STRATEGY;
- if (typeof opts.strategy === 'number') strategy = opts.strategy;
- this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
- this._buffer = Buffer.allocUnsafe(this._chunkSize);
- this._offset = 0;
- this._level = level;
- this._strategy = strategy;
- this.once('end', this.close);
- Object.defineProperty(this, '_closed', {
- get: function () {
- return !_this._handle;
- },
- configurable: true,
- enumerable: true
- });
- }
- util.inherits(Zlib, Transform);
- Zlib.prototype.params = function (level, strategy, callback) {
- if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
- throw new RangeError('Invalid compression level: ' + level);
- }
- if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
- throw new TypeError('Invalid strategy: ' + strategy);
- }
- if (this._level !== level || this._strategy !== strategy) {
- var self = this;
- this.flush(binding.Z_SYNC_FLUSH, function () {
- assert(self._handle, 'zlib binding closed');
- self._handle.params(level, strategy);
- if (!self._hadError) {
- self._level = level;
- self._strategy = strategy;
- if (callback) callback();
- }
- });
- } else {
- process.nextTick(callback);
- }
- };
- Zlib.prototype.reset = function () {
- assert(this._handle, 'zlib binding closed');
- return this._handle.reset();
- };
- // This is the _flush function called by the transform class,
- // internally, when the last chunk has been written.
- Zlib.prototype._flush = function (callback) {
- this._transform(Buffer.alloc(0), '', callback);
- };
- Zlib.prototype.flush = function (kind, callback) {
- var _this2 = this;
- var ws = this._writableState;
- if (typeof kind === 'function' || kind === undefined && !callback) {
- callback = kind;
- kind = binding.Z_FULL_FLUSH;
- }
- if (ws.ended) {
- if (callback) process.nextTick(callback);
- } else if (ws.ending) {
- if (callback) this.once('end', callback);
- } else if (ws.needDrain) {
- if (callback) {
- this.once('drain', function () {
- return _this2.flush(kind, callback);
- });
- }
- } else {
- this._flushFlag = kind;
- this.write(Buffer.alloc(0), '', callback);
- }
- };
- Zlib.prototype.close = function (callback) {
- _close(this, callback);
- process.nextTick(emitCloseNT, this);
- };
- function _close(engine, callback) {
- if (callback) process.nextTick(callback);
- // Caller may invoke .close after a zlib error (which will null _handle).
- if (!engine._handle) return;
- engine._handle.close();
- engine._handle = null;
- }
- function emitCloseNT(self) {
- self.emit('close');
- }
- Zlib.prototype._transform = function (chunk, encoding, cb) {
- var flushFlag;
- var ws = this._writableState;
- var ending = ws.ending || ws.ended;
- var last = ending && (!chunk || ws.length === chunk.length);
- if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
- if (!this._handle) return cb(new Error('zlib binding closed'));
- // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
- // (or whatever flag was provided using opts.finishFlush).
- // If it's explicitly flushing at some other time, then we use
- // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
- // goodness.
- if (last) flushFlag = this._finishFlushFlag;else {
- flushFlag = this._flushFlag;
- // once we've flushed the last of the queue, stop flushing and
- // go back to the normal behavior.
- if (chunk.length >= ws.length) {
- this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
- }
- }
- this._processChunk(chunk, flushFlag, cb);
- };
- Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
- var availInBefore = chunk && chunk.length;
- var availOutBefore = this._chunkSize - this._offset;
- var inOff = 0;
- var self = this;
- var async = typeof cb === 'function';
- if (!async) {
- var buffers = [];
- var nread = 0;
- var error;
- this.on('error', function (er) {
- error = er;
- });
- assert(this._handle, 'zlib binding closed');
- do {
- var res = this._handle.writeSync(flushFlag, chunk, // in
- inOff, // in_off
- availInBefore, // in_len
- this._buffer, // out
- this._offset, //out_off
- availOutBefore); // out_len
- } while (!this._hadError && callback(res[0], res[1]));
- if (this._hadError) {
- throw error;
- }
- if (nread >= kMaxLength) {
- _close(this);
- throw new RangeError(kRangeErrorMessage);
- }
- var buf = Buffer.concat(buffers, nread);
- _close(this);
- return buf;
- }
- assert(this._handle, 'zlib binding closed');
- var req = this._handle.write(flushFlag, chunk, // in
- inOff, // in_off
- availInBefore, // in_len
- this._buffer, // out
- this._offset, //out_off
- availOutBefore); // out_len
- req.buffer = chunk;
- req.callback = callback;
- function callback(availInAfter, availOutAfter) {
- // When the callback is used in an async write, the callback's
- // context is the `req` object that was created. The req object
- // is === this._handle, and that's why it's important to null
- // out the values after they are done being used. `this._handle`
- // can stay in memory longer than the callback and buffer are needed.
- if (this) {
- this.buffer = null;
- this.callback = null;
- }
- if (self._hadError) return;
- var have = availOutBefore - availOutAfter;
- assert(have >= 0, 'have should not go down');
- if (have > 0) {
- var out = self._buffer.slice(self._offset, self._offset + have);
- self._offset += have;
- // serve some output to the consumer.
- if (async) {
- self.push(out);
- } else {
- buffers.push(out);
- nread += out.length;
- }
- }
- // exhausted the output buffer, or used all the input create a new one.
- if (availOutAfter === 0 || self._offset >= self._chunkSize) {
- availOutBefore = self._chunkSize;
- self._offset = 0;
- self._buffer = Buffer.allocUnsafe(self._chunkSize);
- }
- if (availOutAfter === 0) {
- // Not actually done. Need to reprocess.
- // Also, update the availInBefore to the availInAfter value,
- // so that if we have to hit it a third (fourth, etc.) time,
- // it'll have the correct byte counts.
- inOff += availInBefore - availInAfter;
- availInBefore = availInAfter;
- if (!async) return true;
- var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
- newReq.callback = callback; // this same function
- newReq.buffer = chunk;
- return;
- }
- if (!async) return false;
- // finished with the chunk.
- cb();
- }
- };
- util.inherits(Deflate, Zlib);
- util.inherits(Inflate, Zlib);
- util.inherits(Gzip, Zlib);
- util.inherits(Gunzip, Zlib);
- util.inherits(DeflateRaw, Zlib);
- util.inherits(InflateRaw, Zlib);
- util.inherits(Unzip, Zlib);
- }).call(this,require('_process'))
- },{"./binding":33,"_process":312,"assert":24,"buffer":47,"stream":334,"util":365}],35:[function(require,module,exports){
- 'use strict';
- var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
- (typeof Uint16Array !== 'undefined') &&
- (typeof Int32Array !== 'undefined');
- function _has(obj, key) {
- return Object.prototype.hasOwnProperty.call(obj, key);
- }
- exports.assign = function (obj /*from1, from2, from3, ...*/) {
- var sources = Array.prototype.slice.call(arguments, 1);
- while (sources.length) {
- var source = sources.shift();
- if (!source) { continue; }
- if (typeof source !== 'object') {
- throw new TypeError(source + 'must be non-object');
- }
- for (var p in source) {
- if (_has(source, p)) {
- obj[p] = source[p];
- }
- }
- }
- return obj;
- };
- // reduce buffer size, avoiding mem copy
- exports.shrinkBuf = function (buf, size) {
- if (buf.length === size) { return buf; }
- if (buf.subarray) { return buf.subarray(0, size); }
- buf.length = size;
- return buf;
- };
- var fnTyped = {
- arraySet: function (dest, src, src_offs, len, dest_offs) {
- if (src.subarray && dest.subarray) {
- dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
- return;
- }
- // Fallback to ordinary array
- for (var i = 0; i < len; i++) {
- dest[dest_offs + i] = src[src_offs + i];
- }
- },
- // Join array of chunks to single array.
- flattenChunks: function (chunks) {
- var i, l, len, pos, chunk, result;
- // calculate data length
- len = 0;
- for (i = 0, l = chunks.length; i < l; i++) {
- len += chunks[i].length;
- }
- // join chunks
- result = new Uint8Array(len);
- pos = 0;
- for (i = 0, l = chunks.length; i < l; i++) {
- chunk = chunks[i];
- result.set(chunk, pos);
- pos += chunk.length;
- }
- return result;
- }
- };
- var fnUntyped = {
- arraySet: function (dest, src, src_offs, len, dest_offs) {
- for (var i = 0; i < len; i++) {
- dest[dest_offs + i] = src[src_offs + i];
- }
- },
- // Join array of chunks to single array.
- flattenChunks: function (chunks) {
- return [].concat.apply([], chunks);
- }
- };
- // Enable/Disable typed arrays use, for testing
- //
- exports.setTyped = function (on) {
- if (on) {
- exports.Buf8 = Uint8Array;
- exports.Buf16 = Uint16Array;
- exports.Buf32 = Int32Array;
- exports.assign(exports, fnTyped);
- } else {
- exports.Buf8 = Array;
- exports.Buf16 = Array;
- exports.Buf32 = Array;
- exports.assign(exports, fnUntyped);
- }
- };
- exports.setTyped(TYPED_OK);
- },{}],36:[function(require,module,exports){
- 'use strict';
- // Note: adler32 takes 12% for level 0 and 2% for level 6.
- // It isn't worth it to make additional optimizations as in original.
- // Small size is preferable.
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- function adler32(adler, buf, len, pos) {
- var s1 = (adler & 0xffff) |0,
- s2 = ((adler >>> 16) & 0xffff) |0,
- n = 0;
- while (len !== 0) {
- // Set limit ~ twice less than 5552, to keep
- // s2 in 31-bits, because we force signed ints.
- // in other case %= will fail.
- n = len > 2000 ? 2000 : len;
- len -= n;
- do {
- s1 = (s1 + buf[pos++]) |0;
- s2 = (s2 + s1) |0;
- } while (--n);
- s1 %= 65521;
- s2 %= 65521;
- }
- return (s1 | (s2 << 16)) |0;
- }
- module.exports = adler32;
- },{}],37:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- module.exports = {
- /* Allowed flush values; see deflate() and inflate() below for details */
- Z_NO_FLUSH: 0,
- Z_PARTIAL_FLUSH: 1,
- Z_SYNC_FLUSH: 2,
- Z_FULL_FLUSH: 3,
- Z_FINISH: 4,
- Z_BLOCK: 5,
- Z_TREES: 6,
- /* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
- Z_OK: 0,
- Z_STREAM_END: 1,
- Z_NEED_DICT: 2,
- Z_ERRNO: -1,
- Z_STREAM_ERROR: -2,
- Z_DATA_ERROR: -3,
- //Z_MEM_ERROR: -4,
- Z_BUF_ERROR: -5,
- //Z_VERSION_ERROR: -6,
- /* compression levels */
- Z_NO_COMPRESSION: 0,
- Z_BEST_SPEED: 1,
- Z_BEST_COMPRESSION: 9,
- Z_DEFAULT_COMPRESSION: -1,
- Z_FILTERED: 1,
- Z_HUFFMAN_ONLY: 2,
- Z_RLE: 3,
- Z_FIXED: 4,
- Z_DEFAULT_STRATEGY: 0,
- /* Possible values of the data_type field (though see inflate()) */
- Z_BINARY: 0,
- Z_TEXT: 1,
- //Z_ASCII: 1, // = Z_TEXT (deprecated)
- Z_UNKNOWN: 2,
- /* The deflate compression method */
- Z_DEFLATED: 8
- //Z_NULL: null // Use -1 or null inline, depending on var type
- };
- },{}],38:[function(require,module,exports){
- 'use strict';
- // Note: we can't get significant speed boost here.
- // So write code to minimize size - no pregenerated tables
- // and array tools dependencies.
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- // Use ordinary array, since untyped makes no boost here
- function makeTable() {
- var c, table = [];
- for (var n = 0; n < 256; n++) {
- c = n;
- for (var k = 0; k < 8; k++) {
- c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
- }
- table[n] = c;
- }
- return table;
- }
- // Create table on load. Just 255 signed longs. Not a problem.
- var crcTable = makeTable();
- function crc32(crc, buf, len, pos) {
- var t = crcTable,
- end = pos + len;
- crc ^= -1;
- for (var i = pos; i < end; i++) {
- crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
- }
- return (crc ^ (-1)); // >>> 0;
- }
- module.exports = crc32;
- },{}],39:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- var utils = require('../utils/common');
- var trees = require('./trees');
- var adler32 = require('./adler32');
- var crc32 = require('./crc32');
- var msg = require('./messages');
- /* Public constants ==========================================================*/
- /* ===========================================================================*/
- /* Allowed flush values; see deflate() and inflate() below for details */
- var Z_NO_FLUSH = 0;
- var Z_PARTIAL_FLUSH = 1;
- //var Z_SYNC_FLUSH = 2;
- var Z_FULL_FLUSH = 3;
- var Z_FINISH = 4;
- var Z_BLOCK = 5;
- //var Z_TREES = 6;
- /* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
- var Z_OK = 0;
- var Z_STREAM_END = 1;
- //var Z_NEED_DICT = 2;
- //var Z_ERRNO = -1;
- var Z_STREAM_ERROR = -2;
- var Z_DATA_ERROR = -3;
- //var Z_MEM_ERROR = -4;
- var Z_BUF_ERROR = -5;
- //var Z_VERSION_ERROR = -6;
- /* compression levels */
- //var Z_NO_COMPRESSION = 0;
- //var Z_BEST_SPEED = 1;
- //var Z_BEST_COMPRESSION = 9;
- var Z_DEFAULT_COMPRESSION = -1;
- var Z_FILTERED = 1;
- var Z_HUFFMAN_ONLY = 2;
- var Z_RLE = 3;
- var Z_FIXED = 4;
- var Z_DEFAULT_STRATEGY = 0;
- /* Possible values of the data_type field (though see inflate()) */
- //var Z_BINARY = 0;
- //var Z_TEXT = 1;
- //var Z_ASCII = 1; // = Z_TEXT
- var Z_UNKNOWN = 2;
- /* The deflate compression method */
- var Z_DEFLATED = 8;
- /*============================================================================*/
- var MAX_MEM_LEVEL = 9;
- /* Maximum value for memLevel in deflateInit2 */
- var MAX_WBITS = 15;
- /* 32K LZ77 window */
- var DEF_MEM_LEVEL = 8;
- var LENGTH_CODES = 29;
- /* number of length codes, not counting the special END_BLOCK code */
- var LITERALS = 256;
- /* number of literal bytes 0..255 */
- var L_CODES = LITERALS + 1 + LENGTH_CODES;
- /* number of Literal or Length codes, including the END_BLOCK code */
- var D_CODES = 30;
- /* number of distance codes */
- var BL_CODES = 19;
- /* number of codes used to transfer the bit lengths */
- var HEAP_SIZE = 2 * L_CODES + 1;
- /* maximum heap size */
- var MAX_BITS = 15;
- /* All codes must not exceed MAX_BITS bits */
- var MIN_MATCH = 3;
- var MAX_MATCH = 258;
- var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
- var PRESET_DICT = 0x20;
- var INIT_STATE = 42;
- var EXTRA_STATE = 69;
- var NAME_STATE = 73;
- var COMMENT_STATE = 91;
- var HCRC_STATE = 103;
- var BUSY_STATE = 113;
- var FINISH_STATE = 666;
- var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
- var BS_BLOCK_DONE = 2; /* block flush performed */
- var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
- var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
- var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
- function err(strm, errorCode) {
- strm.msg = msg[errorCode];
- return errorCode;
- }
- function rank(f) {
- return ((f) << 1) - ((f) > 4 ? 9 : 0);
- }
- function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
- /* =========================================================================
- * Flush as much pending output as possible. All deflate() output goes
- * through this function so some applications may wish to modify it
- * to avoid allocating a large strm->output buffer and copying into it.
- * (See also read_buf()).
- */
- function flush_pending(strm) {
- var s = strm.state;
- //_tr_flush_bits(s);
- var len = s.pending;
- if (len > strm.avail_out) {
- len = strm.avail_out;
- }
- if (len === 0) { return; }
- utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
- strm.next_out += len;
- s.pending_out += len;
- strm.total_out += len;
- strm.avail_out -= len;
- s.pending -= len;
- if (s.pending === 0) {
- s.pending_out = 0;
- }
- }
- function flush_block_only(s, last) {
- trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
- s.block_start = s.strstart;
- flush_pending(s.strm);
- }
- function put_byte(s, b) {
- s.pending_buf[s.pending++] = b;
- }
- /* =========================================================================
- * Put a short in the pending buffer. The 16-bit value is put in MSB order.
- * IN assertion: the stream state is correct and there is enough room in
- * pending_buf.
- */
- function putShortMSB(s, b) {
- // put_byte(s, (Byte)(b >> 8));
- // put_byte(s, (Byte)(b & 0xff));
- s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
- s.pending_buf[s.pending++] = b & 0xff;
- }
- /* ===========================================================================
- * Read a new buffer from the current input stream, update the adler32
- * and total number of bytes read. All deflate() input goes through
- * this function so some applications may wish to modify it to avoid
- * allocating a large strm->input buffer and copying from it.
- * (See also flush_pending()).
- */
- function read_buf(strm, buf, start, size) {
- var len = strm.avail_in;
- if (len > size) { len = size; }
- if (len === 0) { return 0; }
- strm.avail_in -= len;
- // zmemcpy(buf, strm->next_in, len);
- utils.arraySet(buf, strm.input, strm.next_in, len, start);
- if (strm.state.wrap === 1) {
- strm.adler = adler32(strm.adler, buf, len, start);
- }
- else if (strm.state.wrap === 2) {
- strm.adler = crc32(strm.adler, buf, len, start);
- }
- strm.next_in += len;
- strm.total_in += len;
- return len;
- }
- /* ===========================================================================
- * Set match_start to the longest match starting at the given string and
- * return its length. Matches shorter or equal to prev_length are discarded,
- * in which case the result is equal to prev_length and match_start is
- * garbage.
- * IN assertions: cur_match is the head of the hash chain for the current
- * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
- * OUT assertion: the match length is not greater than s->lookahead.
- */
- function longest_match(s, cur_match) {
- var chain_length = s.max_chain_length; /* max hash chain length */
- var scan = s.strstart; /* current string */
- var match; /* matched string */
- var len; /* length of current match */
- var best_len = s.prev_length; /* best match length so far */
- var nice_match = s.nice_match; /* stop if match long enough */
- var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
- s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
- var _win = s.window; // shortcut
- var wmask = s.w_mask;
- var prev = s.prev;
- /* Stop when cur_match becomes <= limit. To simplify the code,
- * we prevent matches with the string of window index 0.
- */
- var strend = s.strstart + MAX_MATCH;
- var scan_end1 = _win[scan + best_len - 1];
- var scan_end = _win[scan + best_len];
- /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
- * It is easy to get rid of this optimization if necessary.
- */
- // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
- /* Do not waste too much time if we already have a good match: */
- if (s.prev_length >= s.good_match) {
- chain_length >>= 2;
- }
- /* Do not look for matches beyond the end of the input. This is necessary
- * to make deflate deterministic.
- */
- if (nice_match > s.lookahead) { nice_match = s.lookahead; }
- // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
- do {
- // Assert(cur_match < s->strstart, "no future");
- match = cur_match;
- /* Skip to next match if the match length cannot increase
- * or if the match length is less than 2. Note that the checks below
- * for insufficient lookahead only occur occasionally for performance
- * reasons. Therefore uninitialized memory will be accessed, and
- * conditional jumps will be made that depend on those values.
- * However the length of the match is limited to the lookahead, so
- * the output of deflate is not affected by the uninitialized values.
- */
- if (_win[match + best_len] !== scan_end ||
- _win[match + best_len - 1] !== scan_end1 ||
- _win[match] !== _win[scan] ||
- _win[++match] !== _win[scan + 1]) {
- continue;
- }
- /* The check at best_len-1 can be removed because it will be made
- * again later. (This heuristic is not always a win.)
- * It is not necessary to compare scan[2] and match[2] since they
- * are always equal when the other bytes match, given that
- * the hash keys are equal and that HASH_BITS >= 8.
- */
- scan += 2;
- match++;
- // Assert(*scan == *match, "match[2]?");
- /* We check for insufficient lookahead only every 8th comparison;
- * the 256th check will be made at strstart+258.
- */
- do {
- /*jshint noempty:false*/
- } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- scan < strend);
- // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
- len = MAX_MATCH - (strend - scan);
- scan = strend - MAX_MATCH;
- if (len > best_len) {
- s.match_start = cur_match;
- best_len = len;
- if (len >= nice_match) {
- break;
- }
- scan_end1 = _win[scan + best_len - 1];
- scan_end = _win[scan + best_len];
- }
- } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
- if (best_len <= s.lookahead) {
- return best_len;
- }
- return s.lookahead;
- }
- /* ===========================================================================
- * Fill the window when the lookahead becomes insufficient.
- * Updates strstart and lookahead.
- *
- * IN assertion: lookahead < MIN_LOOKAHEAD
- * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
- * At least one byte has been read, or avail_in == 0; reads are
- * performed for at least two bytes (required for the zip translate_eol
- * option -- not supported here).
- */
- function fill_window(s) {
- var _w_size = s.w_size;
- var p, n, m, more, str;
- //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
- do {
- more = s.window_size - s.lookahead - s.strstart;
- // JS ints have 32 bit, block below not needed
- /* Deal with !@#$% 64K limit: */
- //if (sizeof(int) <= 2) {
- // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
- // more = wsize;
- //
- // } else if (more == (unsigned)(-1)) {
- // /* Very unlikely, but possible on 16 bit machine if
- // * strstart == 0 && lookahead == 1 (input done a byte at time)
- // */
- // more--;
- // }
- //}
- /* If the window is almost full and there is insufficient lookahead,
- * move the upper half to the lower one to make room in the upper half.
- */
- if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
- utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
- s.match_start -= _w_size;
- s.strstart -= _w_size;
- /* we now have strstart >= MAX_DIST */
- s.block_start -= _w_size;
- /* Slide the hash table (could be avoided with 32 bit values
- at the expense of memory usage). We slide even when level == 0
- to keep the hash table consistent if we switch back to level > 0
- later. (Using level 0 permanently is not an optimal usage of
- zlib, so we don't care about this pathological case.)
- */
- n = s.hash_size;
- p = n;
- do {
- m = s.head[--p];
- s.head[p] = (m >= _w_size ? m - _w_size : 0);
- } while (--n);
- n = _w_size;
- p = n;
- do {
- m = s.prev[--p];
- s.prev[p] = (m >= _w_size ? m - _w_size : 0);
- /* If n is not on any hash chain, prev[n] is garbage but
- * its value will never be used.
- */
- } while (--n);
- more += _w_size;
- }
- if (s.strm.avail_in === 0) {
- break;
- }
- /* If there was no sliding:
- * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
- * more == window_size - lookahead - strstart
- * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
- * => more >= window_size - 2*WSIZE + 2
- * In the BIG_MEM or MMAP case (not yet supported),
- * window_size == input_size + MIN_LOOKAHEAD &&
- * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
- * Otherwise, window_size == 2*WSIZE so more >= 2.
- * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
- */
- //Assert(more >= 2, "more < 2");
- n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
- s.lookahead += n;
- /* Initialize the hash value now that we have some input: */
- if (s.lookahead + s.insert >= MIN_MATCH) {
- str = s.strstart - s.insert;
- s.ins_h = s.window[str];
- /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
- //#if MIN_MATCH != 3
- // Call update_hash() MIN_MATCH-3 more times
- //#endif
- while (s.insert) {
- /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
- s.prev[str & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = str;
- str++;
- s.insert--;
- if (s.lookahead + s.insert < MIN_MATCH) {
- break;
- }
- }
- }
- /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
- * but this is not important since only literal bytes will be emitted.
- */
- } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
- /* If the WIN_INIT bytes after the end of the current data have never been
- * written, then zero those bytes in order to avoid memory check reports of
- * the use of uninitialized (or uninitialised as Julian writes) bytes by
- * the longest match routines. Update the high water mark for the next
- * time through here. WIN_INIT is set to MAX_MATCH since the longest match
- * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
- */
- // if (s.high_water < s.window_size) {
- // var curr = s.strstart + s.lookahead;
- // var init = 0;
- //
- // if (s.high_water < curr) {
- // /* Previous high water mark below current data -- zero WIN_INIT
- // * bytes or up to end of window, whichever is less.
- // */
- // init = s.window_size - curr;
- // if (init > WIN_INIT)
- // init = WIN_INIT;
- // zmemzero(s->window + curr, (unsigned)init);
- // s->high_water = curr + init;
- // }
- // else if (s->high_water < (ulg)curr + WIN_INIT) {
- // /* High water mark at or above current data, but below current data
- // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
- // * to end of window, whichever is less.
- // */
- // init = (ulg)curr + WIN_INIT - s->high_water;
- // if (init > s->window_size - s->high_water)
- // init = s->window_size - s->high_water;
- // zmemzero(s->window + s->high_water, (unsigned)init);
- // s->high_water += init;
- // }
- // }
- //
- // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
- // "not enough room for search");
- }
- /* ===========================================================================
- * Copy without compression as much as possible from the input stream, return
- * the current block state.
- * This function does not insert new strings in the dictionary since
- * uncompressible data is probably not useful. This function is used
- * only for the level=0 compression option.
- * NOTE: this function should be optimized to avoid extra copying from
- * window to pending_buf.
- */
- function deflate_stored(s, flush) {
- /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
- * to pending_buf_size, and each stored block has a 5 byte header:
- */
- var max_block_size = 0xffff;
- if (max_block_size > s.pending_buf_size - 5) {
- max_block_size = s.pending_buf_size - 5;
- }
- /* Copy as much as possible from input to output: */
- for (;;) {
- /* Fill the window as much as possible: */
- if (s.lookahead <= 1) {
- //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
- // s->block_start >= (long)s->w_size, "slide too late");
- // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
- // s.block_start >= s.w_size)) {
- // throw new Error("slide too late");
- // }
- fill_window(s);
- if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) {
- break;
- }
- /* flush the current block */
- }
- //Assert(s->block_start >= 0L, "block gone");
- // if (s.block_start < 0) throw new Error("block gone");
- s.strstart += s.lookahead;
- s.lookahead = 0;
- /* Emit a stored block if pending_buf will be full: */
- var max_start = s.block_start + max_block_size;
- if (s.strstart === 0 || s.strstart >= max_start) {
- /* strstart == 0 is possible when wraparound on 16-bit machine */
- s.lookahead = s.strstart - max_start;
- s.strstart = max_start;
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- /* Flush if we may have to slide, otherwise block_start may become
- * negative and the data will be gone:
- */
- if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.strstart > s.block_start) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_NEED_MORE;
- }
- /* ===========================================================================
- * Compress as much as possible from the input stream, return the current
- * block state.
- * This function does not perform lazy evaluation of matches and inserts
- * new strings in the dictionary only for unmatched strings or for short
- * matches. It is used only for the fast compression options.
- */
- function deflate_fast(s, flush) {
- var hash_head; /* head of the hash chain */
- var bflush; /* set if current block must be flushed */
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the next match, plus MIN_MATCH bytes to insert the
- * string following the next match.
- */
- if (s.lookahead < MIN_LOOKAHEAD) {
- fill_window(s);
- if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) {
- break; /* flush the current block */
- }
- }
- /* Insert the string window[strstart .. strstart+2] in the
- * dictionary, and set hash_head to the head of the hash chain:
- */
- hash_head = 0/*NIL*/;
- if (s.lookahead >= MIN_MATCH) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
- /* Find the longest match, discarding those <= prev_length.
- * At this point we have always match_length < MIN_MATCH
- */
- if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
- /* To simplify the code, we prevent matches with the string
- * of window index 0 (in particular we have to avoid a match
- * of the string with itself at the start of the input file).
- */
- s.match_length = longest_match(s, hash_head);
- /* longest_match() sets match_start */
- }
- if (s.match_length >= MIN_MATCH) {
- // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
- /*** _tr_tally_dist(s, s.strstart - s.match_start,
- s.match_length - MIN_MATCH, bflush); ***/
- bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
- s.lookahead -= s.match_length;
- /* Insert new strings in the hash table only if the match length
- * is not too large. This saves time but degrades compression.
- */
- if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
- s.match_length--; /* string at strstart already in table */
- do {
- s.strstart++;
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- /* strstart never exceeds WSIZE-MAX_MATCH, so there are
- * always MIN_MATCH bytes ahead.
- */
- } while (--s.match_length !== 0);
- s.strstart++;
- } else
- {
- s.strstart += s.match_length;
- s.match_length = 0;
- s.ins_h = s.window[s.strstart];
- /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
- //#if MIN_MATCH != 3
- // Call UPDATE_HASH() MIN_MATCH-3 more times
- //#endif
- /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
- * matter since it will be recomputed at next deflate call.
- */
- }
- } else {
- /* No match, output a literal byte */
- //Tracevv((stderr,"%c", s.window[s.strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
- s.lookahead--;
- s.strstart++;
- }
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* ===========================================================================
- * Same as above, but achieves better compression. We use a lazy
- * evaluation for matches: a match is finally adopted only if there is
- * no better match at the next window position.
- */
- function deflate_slow(s, flush) {
- var hash_head; /* head of hash chain */
- var bflush; /* set if current block must be flushed */
- var max_insert;
- /* Process the input block. */
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the next match, plus MIN_MATCH bytes to insert the
- * string following the next match.
- */
- if (s.lookahead < MIN_LOOKAHEAD) {
- fill_window(s);
- if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) { break; } /* flush the current block */
- }
- /* Insert the string window[strstart .. strstart+2] in the
- * dictionary, and set hash_head to the head of the hash chain:
- */
- hash_head = 0/*NIL*/;
- if (s.lookahead >= MIN_MATCH) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
- /* Find the longest match, discarding those <= prev_length.
- */
- s.prev_length = s.match_length;
- s.prev_match = s.match_start;
- s.match_length = MIN_MATCH - 1;
- if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
- s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
- /* To simplify the code, we prevent matches with the string
- * of window index 0 (in particular we have to avoid a match
- * of the string with itself at the start of the input file).
- */
- s.match_length = longest_match(s, hash_head);
- /* longest_match() sets match_start */
- if (s.match_length <= 5 &&
- (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
- /* If prev_match is also MIN_MATCH, match_start is garbage
- * but we will ignore the current match anyway.
- */
- s.match_length = MIN_MATCH - 1;
- }
- }
- /* If there was a match at the previous step and the current
- * match is not better, output the previous match:
- */
- if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
- max_insert = s.strstart + s.lookahead - MIN_MATCH;
- /* Do not insert strings in hash table beyond this. */
- //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
- /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
- s.prev_length - MIN_MATCH, bflush);***/
- bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
- /* Insert in hash table all strings up to the end of the match.
- * strstart-1 and strstart are already inserted. If there is not
- * enough lookahead, the last two strings are not inserted in
- * the hash table.
- */
- s.lookahead -= s.prev_length - 1;
- s.prev_length -= 2;
- do {
- if (++s.strstart <= max_insert) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
- } while (--s.prev_length !== 0);
- s.match_available = 0;
- s.match_length = MIN_MATCH - 1;
- s.strstart++;
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- } else if (s.match_available) {
- /* If there was no match at the previous position, output a
- * single literal. If there was a match but the current match
- * is longer, truncate the previous match to a single literal.
- */
- //Tracevv((stderr,"%c", s->window[s->strstart-1]));
- /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
- if (bflush) {
- /*** FLUSH_BLOCK_ONLY(s, 0) ***/
- flush_block_only(s, false);
- /***/
- }
- s.strstart++;
- s.lookahead--;
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- } else {
- /* There is no previous match to compare with, wait for
- * the next step to decide.
- */
- s.match_available = 1;
- s.strstart++;
- s.lookahead--;
- }
- }
- //Assert (flush != Z_NO_FLUSH, "no flush?");
- if (s.match_available) {
- //Tracevv((stderr,"%c", s->window[s->strstart-1]));
- /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
- s.match_available = 0;
- }
- s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* ===========================================================================
- * For Z_RLE, simply look for runs of bytes, generate matches only of distance
- * one. Do not maintain a hash table. (It will be regenerated if this run of
- * deflate switches away from Z_RLE.)
- */
- function deflate_rle(s, flush) {
- var bflush; /* set if current block must be flushed */
- var prev; /* byte at distance one to match */
- var scan, strend; /* scan goes up to strend for length of run */
- var _win = s.window;
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the longest run, plus one for the unrolled loop.
- */
- if (s.lookahead <= MAX_MATCH) {
- fill_window(s);
- if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) { break; } /* flush the current block */
- }
- /* See how many times the previous byte repeats */
- s.match_length = 0;
- if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
- scan = s.strstart - 1;
- prev = _win[scan];
- if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
- strend = s.strstart + MAX_MATCH;
- do {
- /*jshint noempty:false*/
- } while (prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- scan < strend);
- s.match_length = MAX_MATCH - (strend - scan);
- if (s.match_length > s.lookahead) {
- s.match_length = s.lookahead;
- }
- }
- //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
- }
- /* Emit match if have run of MIN_MATCH or longer, else emit literal */
- if (s.match_length >= MIN_MATCH) {
- //check_match(s, s.strstart, s.strstart - 1, s.match_length);
- /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
- bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
- s.lookahead -= s.match_length;
- s.strstart += s.match_length;
- s.match_length = 0;
- } else {
- /* No match, output a literal byte */
- //Tracevv((stderr,"%c", s->window[s->strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
- s.lookahead--;
- s.strstart++;
- }
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* ===========================================================================
- * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
- * (It will be regenerated if this run of deflate switches away from Huffman.)
- */
- function deflate_huff(s, flush) {
- var bflush; /* set if current block must be flushed */
- for (;;) {
- /* Make sure that we have a literal to write. */
- if (s.lookahead === 0) {
- fill_window(s);
- if (s.lookahead === 0) {
- if (flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- break; /* flush the current block */
- }
- }
- /* Output a literal byte */
- s.match_length = 0;
- //Tracevv((stderr,"%c", s->window[s->strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
- s.lookahead--;
- s.strstart++;
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* Values for max_lazy_match, good_match and max_chain_length, depending on
- * the desired pack level (0..9). The values given below have been tuned to
- * exclude worst case performance for pathological files. Better values may be
- * found for specific files.
- */
- function Config(good_length, max_lazy, nice_length, max_chain, func) {
- this.good_length = good_length;
- this.max_lazy = max_lazy;
- this.nice_length = nice_length;
- this.max_chain = max_chain;
- this.func = func;
- }
- var configuration_table;
- configuration_table = [
- /* good lazy nice chain */
- new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
- new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
- new Config(4, 5, 16, 8, deflate_fast), /* 2 */
- new Config(4, 6, 32, 32, deflate_fast), /* 3 */
- new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
- new Config(8, 16, 32, 32, deflate_slow), /* 5 */
- new Config(8, 16, 128, 128, deflate_slow), /* 6 */
- new Config(8, 32, 128, 256, deflate_slow), /* 7 */
- new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
- new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
- ];
- /* ===========================================================================
- * Initialize the "longest match" routines for a new zlib stream
- */
- function lm_init(s) {
- s.window_size = 2 * s.w_size;
- /*** CLEAR_HASH(s); ***/
- zero(s.head); // Fill with NIL (= 0);
- /* Set the default configuration parameters:
- */
- s.max_lazy_match = configuration_table[s.level].max_lazy;
- s.good_match = configuration_table[s.level].good_length;
- s.nice_match = configuration_table[s.level].nice_length;
- s.max_chain_length = configuration_table[s.level].max_chain;
- s.strstart = 0;
- s.block_start = 0;
- s.lookahead = 0;
- s.insert = 0;
- s.match_length = s.prev_length = MIN_MATCH - 1;
- s.match_available = 0;
- s.ins_h = 0;
- }
- function DeflateState() {
- this.strm = null; /* pointer back to this zlib stream */
- this.status = 0; /* as the name implies */
- this.pending_buf = null; /* output still pending */
- this.pending_buf_size = 0; /* size of pending_buf */
- this.pending_out = 0; /* next pending byte to output to the stream */
- this.pending = 0; /* nb of bytes in the pending buffer */
- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
- this.gzhead = null; /* gzip header information to write */
- this.gzindex = 0; /* where in extra, name, or comment */
- this.method = Z_DEFLATED; /* can only be DEFLATED */
- this.last_flush = -1; /* value of flush param for previous deflate call */
- this.w_size = 0; /* LZ77 window size (32K by default) */
- this.w_bits = 0; /* log2(w_size) (8..16) */
- this.w_mask = 0; /* w_size - 1 */
- this.window = null;
- /* Sliding window. Input bytes are read into the second half of the window,
- * and move to the first half later to keep a dictionary of at least wSize
- * bytes. With this organization, matches are limited to a distance of
- * wSize-MAX_MATCH bytes, but this ensures that IO is always
- * performed with a length multiple of the block size.
- */
- this.window_size = 0;
- /* Actual size of window: 2*wSize, except when the user input buffer
- * is directly used as sliding window.
- */
- this.prev = null;
- /* Link to older string with same hash index. To limit the size of this
- * array to 64K, this link is maintained only for the last 32K strings.
- * An index in this array is thus a window index modulo 32K.
- */
- this.head = null; /* Heads of the hash chains or NIL. */
- this.ins_h = 0; /* hash index of string to be inserted */
- this.hash_size = 0; /* number of elements in hash table */
- this.hash_bits = 0; /* log2(hash_size) */
- this.hash_mask = 0; /* hash_size-1 */
- this.hash_shift = 0;
- /* Number of bits by which ins_h must be shifted at each input
- * step. It must be such that after MIN_MATCH steps, the oldest
- * byte no longer takes part in the hash key, that is:
- * hash_shift * MIN_MATCH >= hash_bits
- */
- this.block_start = 0;
- /* Window position at the beginning of the current output block. Gets
- * negative when the window is moved backwards.
- */
- this.match_length = 0; /* length of best match */
- this.prev_match = 0; /* previous match */
- this.match_available = 0; /* set if previous match exists */
- this.strstart = 0; /* start of string to insert */
- this.match_start = 0; /* start of matching string */
- this.lookahead = 0; /* number of valid bytes ahead in window */
- this.prev_length = 0;
- /* Length of the best match at previous step. Matches not greater than this
- * are discarded. This is used in the lazy match evaluation.
- */
- this.max_chain_length = 0;
- /* To speed up deflation, hash chains are never searched beyond this
- * length. A higher limit improves compression ratio but degrades the
- * speed.
- */
- this.max_lazy_match = 0;
- /* Attempt to find a better match only when the current match is strictly
- * smaller than this value. This mechanism is used only for compression
- * levels >= 4.
- */
- // That's alias to max_lazy_match, don't use directly
- //this.max_insert_length = 0;
- /* Insert new strings in the hash table only if the match length is not
- * greater than this length. This saves time but degrades compression.
- * max_insert_length is used only for compression levels <= 3.
- */
- this.level = 0; /* compression level (1..9) */
- this.strategy = 0; /* favor or force Huffman coding*/
- this.good_match = 0;
- /* Use a faster search when the previous match is longer than this */
- this.nice_match = 0; /* Stop searching when current match exceeds this */
- /* used by trees.c: */
- /* Didn't use ct_data typedef below to suppress compiler warning */
- // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
- // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
- // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
- // Use flat array of DOUBLE size, with interleaved fata,
- // because JS does not support effective
- this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
- this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
- this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
- zero(this.dyn_ltree);
- zero(this.dyn_dtree);
- zero(this.bl_tree);
- this.l_desc = null; /* desc. for literal tree */
- this.d_desc = null; /* desc. for distance tree */
- this.bl_desc = null; /* desc. for bit length tree */
- //ush bl_count[MAX_BITS+1];
- this.bl_count = new utils.Buf16(MAX_BITS + 1);
- /* number of codes at each bit length for an optimal tree */
- //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
- this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
- zero(this.heap);
- this.heap_len = 0; /* number of elements in the heap */
- this.heap_max = 0; /* element of largest frequency */
- /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
- * The same heap array is used to build all trees.
- */
- this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
- zero(this.depth);
- /* Depth of each subtree used as tie breaker for trees of equal frequency
- */
- this.l_buf = 0; /* buffer index for literals or lengths */
- this.lit_bufsize = 0;
- /* Size of match buffer for literals/lengths. There are 4 reasons for
- * limiting lit_bufsize to 64K:
- * - frequencies can be kept in 16 bit counters
- * - if compression is not successful for the first block, all input
- * data is still in the window so we can still emit a stored block even
- * when input comes from standard input. (This can also be done for
- * all blocks if lit_bufsize is not greater than 32K.)
- * - if compression is not successful for a file smaller than 64K, we can
- * even emit a stored file instead of a stored block (saving 5 bytes).
- * This is applicable only for zip (not gzip or zlib).
- * - creating new Huffman trees less frequently may not provide fast
- * adaptation to changes in the input data statistics. (Take for
- * example a binary file with poorly compressible code followed by
- * a highly compressible string table.) Smaller buffer sizes give
- * fast adaptation but have of course the overhead of transmitting
- * trees more frequently.
- * - I can't count above 4
- */
- this.last_lit = 0; /* running index in l_buf */
- this.d_buf = 0;
- /* Buffer index for distances. To simplify the code, d_buf and l_buf have
- * the same number of elements. To use different lengths, an extra flag
- * array would be necessary.
- */
- this.opt_len = 0; /* bit length of current block with optimal trees */
- this.static_len = 0; /* bit length of current block with static trees */
- this.matches = 0; /* number of string matches in current block */
- this.insert = 0; /* bytes at end of window left to insert */
- this.bi_buf = 0;
- /* Output buffer. bits are inserted starting at the bottom (least
- * significant bits).
- */
- this.bi_valid = 0;
- /* Number of valid bits in bi_buf. All bits above the last valid bit
- * are always zero.
- */
- // Used for window memory init. We safely ignore it for JS. That makes
- // sense only for pointers and memory check tools.
- //this.high_water = 0;
- /* High water mark offset in window for initialized bytes -- bytes above
- * this are set to zero in order to avoid memory check warnings when
- * longest match routines access bytes past the input. This is then
- * updated to the new high water mark.
- */
- }
- function deflateResetKeep(strm) {
- var s;
- if (!strm || !strm.state) {
- return err(strm, Z_STREAM_ERROR);
- }
- strm.total_in = strm.total_out = 0;
- strm.data_type = Z_UNKNOWN;
- s = strm.state;
- s.pending = 0;
- s.pending_out = 0;
- if (s.wrap < 0) {
- s.wrap = -s.wrap;
- /* was made negative by deflate(..., Z_FINISH); */
- }
- s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
- strm.adler = (s.wrap === 2) ?
- 0 // crc32(0, Z_NULL, 0)
- :
- 1; // adler32(0, Z_NULL, 0)
- s.last_flush = Z_NO_FLUSH;
- trees._tr_init(s);
- return Z_OK;
- }
- function deflateReset(strm) {
- var ret = deflateResetKeep(strm);
- if (ret === Z_OK) {
- lm_init(strm.state);
- }
- return ret;
- }
- function deflateSetHeader(strm, head) {
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
- strm.state.gzhead = head;
- return Z_OK;
- }
- function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
- if (!strm) { // === Z_NULL
- return Z_STREAM_ERROR;
- }
- var wrap = 1;
- if (level === Z_DEFAULT_COMPRESSION) {
- level = 6;
- }
- if (windowBits < 0) { /* suppress zlib wrapper */
- wrap = 0;
- windowBits = -windowBits;
- }
- else if (windowBits > 15) {
- wrap = 2; /* write gzip wrapper instead */
- windowBits -= 16;
- }
- if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
- windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
- strategy < 0 || strategy > Z_FIXED) {
- return err(strm, Z_STREAM_ERROR);
- }
- if (windowBits === 8) {
- windowBits = 9;
- }
- /* until 256-byte window bug fixed */
- var s = new DeflateState();
- strm.state = s;
- s.strm = strm;
- s.wrap = wrap;
- s.gzhead = null;
- s.w_bits = windowBits;
- s.w_size = 1 << s.w_bits;
- s.w_mask = s.w_size - 1;
- s.hash_bits = memLevel + 7;
- s.hash_size = 1 << s.hash_bits;
- s.hash_mask = s.hash_size - 1;
- s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
- s.window = new utils.Buf8(s.w_size * 2);
- s.head = new utils.Buf16(s.hash_size);
- s.prev = new utils.Buf16(s.w_size);
- // Don't need mem init magic for JS.
- //s.high_water = 0; /* nothing written to s->window yet */
- s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
- s.pending_buf_size = s.lit_bufsize * 4;
- //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
- //s->pending_buf = (uchf *) overlay;
- s.pending_buf = new utils.Buf8(s.pending_buf_size);
- // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
- //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
- s.d_buf = 1 * s.lit_bufsize;
- //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
- s.l_buf = (1 + 2) * s.lit_bufsize;
- s.level = level;
- s.strategy = strategy;
- s.method = method;
- return deflateReset(strm);
- }
- function deflateInit(strm, level) {
- return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
- }
- function deflate(strm, flush) {
- var old_flush, s;
- var beg, val; // for gzip header write only
- if (!strm || !strm.state ||
- flush > Z_BLOCK || flush < 0) {
- return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
- }
- s = strm.state;
- if (!strm.output ||
- (!strm.input && strm.avail_in !== 0) ||
- (s.status === FINISH_STATE && flush !== Z_FINISH)) {
- return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
- }
- s.strm = strm; /* just in case */
- old_flush = s.last_flush;
- s.last_flush = flush;
- /* Write the header */
- if (s.status === INIT_STATE) {
- if (s.wrap === 2) { // GZIP header
- strm.adler = 0; //crc32(0L, Z_NULL, 0);
- put_byte(s, 31);
- put_byte(s, 139);
- put_byte(s, 8);
- if (!s.gzhead) { // s->gzhead == Z_NULL
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, s.level === 9 ? 2 :
- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
- 4 : 0));
- put_byte(s, OS_CODE);
- s.status = BUSY_STATE;
- }
- else {
- put_byte(s, (s.gzhead.text ? 1 : 0) +
- (s.gzhead.hcrc ? 2 : 0) +
- (!s.gzhead.extra ? 0 : 4) +
- (!s.gzhead.name ? 0 : 8) +
- (!s.gzhead.comment ? 0 : 16)
- );
- put_byte(s, s.gzhead.time & 0xff);
- put_byte(s, (s.gzhead.time >> 8) & 0xff);
- put_byte(s, (s.gzhead.time >> 16) & 0xff);
- put_byte(s, (s.gzhead.time >> 24) & 0xff);
- put_byte(s, s.level === 9 ? 2 :
- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
- 4 : 0));
- put_byte(s, s.gzhead.os & 0xff);
- if (s.gzhead.extra && s.gzhead.extra.length) {
- put_byte(s, s.gzhead.extra.length & 0xff);
- put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
- }
- if (s.gzhead.hcrc) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
- }
- s.gzindex = 0;
- s.status = EXTRA_STATE;
- }
- }
- else // DEFLATE header
- {
- var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
- var level_flags = -1;
- if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
- level_flags = 0;
- } else if (s.level < 6) {
- level_flags = 1;
- } else if (s.level === 6) {
- level_flags = 2;
- } else {
- level_flags = 3;
- }
- header |= (level_flags << 6);
- if (s.strstart !== 0) { header |= PRESET_DICT; }
- header += 31 - (header % 31);
- s.status = BUSY_STATE;
- putShortMSB(s, header);
- /* Save the adler32 of the preset dictionary: */
- if (s.strstart !== 0) {
- putShortMSB(s, strm.adler >>> 16);
- putShortMSB(s, strm.adler & 0xffff);
- }
- strm.adler = 1; // adler32(0L, Z_NULL, 0);
- }
- }
- //#ifdef GZIP
- if (s.status === EXTRA_STATE) {
- if (s.gzhead.extra/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- break;
- }
- }
- put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
- s.gzindex++;
- }
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (s.gzindex === s.gzhead.extra.length) {
- s.gzindex = 0;
- s.status = NAME_STATE;
- }
- }
- else {
- s.status = NAME_STATE;
- }
- }
- if (s.status === NAME_STATE) {
- if (s.gzhead.name/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- //int val;
- do {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- val = 1;
- break;
- }
- }
- // JS specific: little magic to add zero terminator to end of string
- if (s.gzindex < s.gzhead.name.length) {
- val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
- } else {
- val = 0;
- }
- put_byte(s, val);
- } while (val !== 0);
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (val === 0) {
- s.gzindex = 0;
- s.status = COMMENT_STATE;
- }
- }
- else {
- s.status = COMMENT_STATE;
- }
- }
- if (s.status === COMMENT_STATE) {
- if (s.gzhead.comment/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- //int val;
- do {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- val = 1;
- break;
- }
- }
- // JS specific: little magic to add zero terminator to end of string
- if (s.gzindex < s.gzhead.comment.length) {
- val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
- } else {
- val = 0;
- }
- put_byte(s, val);
- } while (val !== 0);
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (val === 0) {
- s.status = HCRC_STATE;
- }
- }
- else {
- s.status = HCRC_STATE;
- }
- }
- if (s.status === HCRC_STATE) {
- if (s.gzhead.hcrc) {
- if (s.pending + 2 > s.pending_buf_size) {
- flush_pending(strm);
- }
- if (s.pending + 2 <= s.pending_buf_size) {
- put_byte(s, strm.adler & 0xff);
- put_byte(s, (strm.adler >> 8) & 0xff);
- strm.adler = 0; //crc32(0L, Z_NULL, 0);
- s.status = BUSY_STATE;
- }
- }
- else {
- s.status = BUSY_STATE;
- }
- }
- //#endif
- /* Flush as much pending output as possible */
- if (s.pending !== 0) {
- flush_pending(strm);
- if (strm.avail_out === 0) {
- /* Since avail_out is 0, deflate will be called again with
- * more output space, but possibly with both pending and
- * avail_in equal to zero. There won't be anything to do,
- * but this is not an error situation so make sure we
- * return OK instead of BUF_ERROR at next call of deflate:
- */
- s.last_flush = -1;
- return Z_OK;
- }
- /* Make sure there is something to do and avoid duplicate consecutive
- * flushes. For repeated and useless calls with Z_FINISH, we keep
- * returning Z_STREAM_END instead of Z_BUF_ERROR.
- */
- } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
- flush !== Z_FINISH) {
- return err(strm, Z_BUF_ERROR);
- }
- /* User must not provide more input after the first FINISH: */
- if (s.status === FINISH_STATE && strm.avail_in !== 0) {
- return err(strm, Z_BUF_ERROR);
- }
- /* Start a new block or continue the current one.
- */
- if (strm.avail_in !== 0 || s.lookahead !== 0 ||
- (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
- var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
- (s.strategy === Z_RLE ? deflate_rle(s, flush) :
- configuration_table[s.level].func(s, flush));
- if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
- s.status = FINISH_STATE;
- }
- if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
- if (strm.avail_out === 0) {
- s.last_flush = -1;
- /* avoid BUF_ERROR next call, see above */
- }
- return Z_OK;
- /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
- * of deflate should use the same flush parameter to make sure
- * that the flush is complete. So we don't have to output an
- * empty block here, this will be done at next call. This also
- * ensures that for a very small output buffer, we emit at most
- * one empty block.
- */
- }
- if (bstate === BS_BLOCK_DONE) {
- if (flush === Z_PARTIAL_FLUSH) {
- trees._tr_align(s);
- }
- else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
- trees._tr_stored_block(s, 0, 0, false);
- /* For a full flush, this empty block will be recognized
- * as a special marker by inflate_sync().
- */
- if (flush === Z_FULL_FLUSH) {
- /*** CLEAR_HASH(s); ***/ /* forget history */
- zero(s.head); // Fill with NIL (= 0);
- if (s.lookahead === 0) {
- s.strstart = 0;
- s.block_start = 0;
- s.insert = 0;
- }
- }
- }
- flush_pending(strm);
- if (strm.avail_out === 0) {
- s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
- return Z_OK;
- }
- }
- }
- //Assert(strm->avail_out > 0, "bug2");
- //if (strm.avail_out <= 0) { throw new Error("bug2");}
- if (flush !== Z_FINISH) { return Z_OK; }
- if (s.wrap <= 0) { return Z_STREAM_END; }
- /* Write the trailer */
- if (s.wrap === 2) {
- put_byte(s, strm.adler & 0xff);
- put_byte(s, (strm.adler >> 8) & 0xff);
- put_byte(s, (strm.adler >> 16) & 0xff);
- put_byte(s, (strm.adler >> 24) & 0xff);
- put_byte(s, strm.total_in & 0xff);
- put_byte(s, (strm.total_in >> 8) & 0xff);
- put_byte(s, (strm.total_in >> 16) & 0xff);
- put_byte(s, (strm.total_in >> 24) & 0xff);
- }
- else
- {
- putShortMSB(s, strm.adler >>> 16);
- putShortMSB(s, strm.adler & 0xffff);
- }
- flush_pending(strm);
- /* If avail_out is zero, the application will call deflate again
- * to flush the rest.
- */
- if (s.wrap > 0) { s.wrap = -s.wrap; }
- /* write the trailer only once! */
- return s.pending !== 0 ? Z_OK : Z_STREAM_END;
- }
- function deflateEnd(strm) {
- var status;
- if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
- return Z_STREAM_ERROR;
- }
- status = strm.state.status;
- if (status !== INIT_STATE &&
- status !== EXTRA_STATE &&
- status !== NAME_STATE &&
- status !== COMMENT_STATE &&
- status !== HCRC_STATE &&
- status !== BUSY_STATE &&
- status !== FINISH_STATE
- ) {
- return err(strm, Z_STREAM_ERROR);
- }
- strm.state = null;
- return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
- }
- /* =========================================================================
- * Initializes the compression dictionary from the given byte
- * sequence without producing any compressed output.
- */
- function deflateSetDictionary(strm, dictionary) {
- var dictLength = dictionary.length;
- var s;
- var str, n;
- var wrap;
- var avail;
- var next;
- var input;
- var tmpDict;
- if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
- return Z_STREAM_ERROR;
- }
- s = strm.state;
- wrap = s.wrap;
- if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
- return Z_STREAM_ERROR;
- }
- /* when using zlib wrappers, compute Adler-32 for provided dictionary */
- if (wrap === 1) {
- /* adler32(strm->adler, dictionary, dictLength); */
- strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
- }
- s.wrap = 0; /* avoid computing Adler-32 in read_buf */
- /* if dictionary would fill window, just replace the history */
- if (dictLength >= s.w_size) {
- if (wrap === 0) { /* already empty otherwise */
- /*** CLEAR_HASH(s); ***/
- zero(s.head); // Fill with NIL (= 0);
- s.strstart = 0;
- s.block_start = 0;
- s.insert = 0;
- }
- /* use the tail */
- // dictionary = dictionary.slice(dictLength - s.w_size);
- tmpDict = new utils.Buf8(s.w_size);
- utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
- dictionary = tmpDict;
- dictLength = s.w_size;
- }
- /* insert dictionary into window and hash */
- avail = strm.avail_in;
- next = strm.next_in;
- input = strm.input;
- strm.avail_in = dictLength;
- strm.next_in = 0;
- strm.input = dictionary;
- fill_window(s);
- while (s.lookahead >= MIN_MATCH) {
- str = s.strstart;
- n = s.lookahead - (MIN_MATCH - 1);
- do {
- /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
- s.prev[str & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = str;
- str++;
- } while (--n);
- s.strstart = str;
- s.lookahead = MIN_MATCH - 1;
- fill_window(s);
- }
- s.strstart += s.lookahead;
- s.block_start = s.strstart;
- s.insert = s.lookahead;
- s.lookahead = 0;
- s.match_length = s.prev_length = MIN_MATCH - 1;
- s.match_available = 0;
- strm.next_in = next;
- strm.input = input;
- strm.avail_in = avail;
- s.wrap = wrap;
- return Z_OK;
- }
- exports.deflateInit = deflateInit;
- exports.deflateInit2 = deflateInit2;
- exports.deflateReset = deflateReset;
- exports.deflateResetKeep = deflateResetKeep;
- exports.deflateSetHeader = deflateSetHeader;
- exports.deflate = deflate;
- exports.deflateEnd = deflateEnd;
- exports.deflateSetDictionary = deflateSetDictionary;
- exports.deflateInfo = 'pako deflate (from Nodeca project)';
- /* Not implemented
- exports.deflateBound = deflateBound;
- exports.deflateCopy = deflateCopy;
- exports.deflateParams = deflateParams;
- exports.deflatePending = deflatePending;
- exports.deflatePrime = deflatePrime;
- exports.deflateTune = deflateTune;
- */
- },{"../utils/common":35,"./adler32":36,"./crc32":38,"./messages":43,"./trees":44}],40:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- // See state defs from inflate.js
- var BAD = 30; /* got a data error -- remain here until reset */
- var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
- /*
- Decode literal, length, and distance codes and write out the resulting
- literal and match bytes until either not enough input or output is
- available, an end-of-block is encountered, or a data error is encountered.
- When large enough input and output buffers are supplied to inflate(), for
- example, a 16K input buffer and a 64K output buffer, more than 95% of the
- inflate execution time is spent in this routine.
- Entry assumptions:
- state.mode === LEN
- strm.avail_in >= 6
- strm.avail_out >= 258
- start >= strm.avail_out
- state.bits < 8
- On return, state.mode is one of:
- LEN -- ran out of enough output space or enough available input
- TYPE -- reached end of block code, inflate() to interpret next block
- BAD -- error in block data
- Notes:
- - The maximum input bits used by a length/distance pair is 15 bits for the
- length code, 5 bits for the length extra, 15 bits for the distance code,
- and 13 bits for the distance extra. This totals 48 bits, or six bytes.
- Therefore if strm.avail_in >= 6, then there is enough input to avoid
- checking for available input while decoding.
- - The maximum bytes that a single length/distance pair can output is 258
- bytes, which is the maximum length that can be coded. inflate_fast()
- requires strm.avail_out >= 258 for each loop to avoid checking for
- output space.
- */
- module.exports = function inflate_fast(strm, start) {
- var state;
- var _in; /* local strm.input */
- var last; /* have enough input while in < last */
- var _out; /* local strm.output */
- var beg; /* inflate()'s initial strm.output */
- var end; /* while out < end, enough space available */
- //#ifdef INFLATE_STRICT
- var dmax; /* maximum distance from zlib header */
- //#endif
- var wsize; /* window size or zero if not using window */
- var whave; /* valid bytes in the window */
- var wnext; /* window write index */
- // Use `s_window` instead `window`, avoid conflict with instrumentation tools
- var s_window; /* allocated sliding window, if wsize != 0 */
- var hold; /* local strm.hold */
- var bits; /* local strm.bits */
- var lcode; /* local strm.lencode */
- var dcode; /* local strm.distcode */
- var lmask; /* mask for first level of length codes */
- var dmask; /* mask for first level of distance codes */
- var here; /* retrieved table entry */
- var op; /* code bits, operation, extra bits, or */
- /* window position, window bytes to copy */
- var len; /* match length, unused bytes */
- var dist; /* match distance */
- var from; /* where to copy match from */
- var from_source;
- var input, output; // JS specific, because we have no pointers
- /* copy state to local variables */
- state = strm.state;
- //here = state.here;
- _in = strm.next_in;
- input = strm.input;
- last = _in + (strm.avail_in - 5);
- _out = strm.next_out;
- output = strm.output;
- beg = _out - (start - strm.avail_out);
- end = _out + (strm.avail_out - 257);
- //#ifdef INFLATE_STRICT
- dmax = state.dmax;
- //#endif
- wsize = state.wsize;
- whave = state.whave;
- wnext = state.wnext;
- s_window = state.window;
- hold = state.hold;
- bits = state.bits;
- lcode = state.lencode;
- dcode = state.distcode;
- lmask = (1 << state.lenbits) - 1;
- dmask = (1 << state.distbits) - 1;
- /* decode literals and length/distances until end-of-block or not enough
- input data or output space */
- top:
- do {
- if (bits < 15) {
- hold += input[_in++] << bits;
- bits += 8;
- hold += input[_in++] << bits;
- bits += 8;
- }
- here = lcode[hold & lmask];
- dolen:
- for (;;) { // Goto emulation
- op = here >>> 24/*here.bits*/;
- hold >>>= op;
- bits -= op;
- op = (here >>> 16) & 0xff/*here.op*/;
- if (op === 0) { /* literal */
- //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
- // "inflate: literal '%c'\n" :
- // "inflate: literal 0x%02x\n", here.val));
- output[_out++] = here & 0xffff/*here.val*/;
- }
- else if (op & 16) { /* length base */
- len = here & 0xffff/*here.val*/;
- op &= 15; /* number of extra bits */
- if (op) {
- if (bits < op) {
- hold += input[_in++] << bits;
- bits += 8;
- }
- len += hold & ((1 << op) - 1);
- hold >>>= op;
- bits -= op;
- }
- //Tracevv((stderr, "inflate: length %u\n", len));
- if (bits < 15) {
- hold += input[_in++] << bits;
- bits += 8;
- hold += input[_in++] << bits;
- bits += 8;
- }
- here = dcode[hold & dmask];
- dodist:
- for (;;) { // goto emulation
- op = here >>> 24/*here.bits*/;
- hold >>>= op;
- bits -= op;
- op = (here >>> 16) & 0xff/*here.op*/;
- if (op & 16) { /* distance base */
- dist = here & 0xffff/*here.val*/;
- op &= 15; /* number of extra bits */
- if (bits < op) {
- hold += input[_in++] << bits;
- bits += 8;
- if (bits < op) {
- hold += input[_in++] << bits;
- bits += 8;
- }
- }
- dist += hold & ((1 << op) - 1);
- //#ifdef INFLATE_STRICT
- if (dist > dmax) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break top;
- }
- //#endif
- hold >>>= op;
- bits -= op;
- //Tracevv((stderr, "inflate: distance %u\n", dist));
- op = _out - beg; /* max distance in output */
- if (dist > op) { /* see if copy from window */
- op = dist - op; /* distance back in window */
- if (op > whave) {
- if (state.sane) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break top;
- }
- // (!) This block is disabled in zlib defaults,
- // don't enable it for binary compatibility
- //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
- // if (len <= op - whave) {
- // do {
- // output[_out++] = 0;
- // } while (--len);
- // continue top;
- // }
- // len -= op - whave;
- // do {
- // output[_out++] = 0;
- // } while (--op > whave);
- // if (op === 0) {
- // from = _out - dist;
- // do {
- // output[_out++] = output[from++];
- // } while (--len);
- // continue top;
- // }
- //#endif
- }
- from = 0; // window index
- from_source = s_window;
- if (wnext === 0) { /* very common case */
- from += wsize - op;
- if (op < len) { /* some from window */
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = _out - dist; /* rest from output */
- from_source = output;
- }
- }
- else if (wnext < op) { /* wrap around window */
- from += wsize + wnext - op;
- op -= wnext;
- if (op < len) { /* some from end of window */
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = 0;
- if (wnext < len) { /* some from start of window */
- op = wnext;
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = _out - dist; /* rest from output */
- from_source = output;
- }
- }
- }
- else { /* contiguous in window */
- from += wnext - op;
- if (op < len) { /* some from window */
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = _out - dist; /* rest from output */
- from_source = output;
- }
- }
- while (len > 2) {
- output[_out++] = from_source[from++];
- output[_out++] = from_source[from++];
- output[_out++] = from_source[from++];
- len -= 3;
- }
- if (len) {
- output[_out++] = from_source[from++];
- if (len > 1) {
- output[_out++] = from_source[from++];
- }
- }
- }
- else {
- from = _out - dist; /* copy direct from output */
- do { /* minimum length is three */
- output[_out++] = output[from++];
- output[_out++] = output[from++];
- output[_out++] = output[from++];
- len -= 3;
- } while (len > 2);
- if (len) {
- output[_out++] = output[from++];
- if (len > 1) {
- output[_out++] = output[from++];
- }
- }
- }
- }
- else if ((op & 64) === 0) { /* 2nd level distance code */
- here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
- continue dodist;
- }
- else {
- strm.msg = 'invalid distance code';
- state.mode = BAD;
- break top;
- }
- break; // need to emulate goto via "continue"
- }
- }
- else if ((op & 64) === 0) { /* 2nd level length code */
- here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
- continue dolen;
- }
- else if (op & 32) { /* end-of-block */
- //Tracevv((stderr, "inflate: end of block\n"));
- state.mode = TYPE;
- break top;
- }
- else {
- strm.msg = 'invalid literal/length code';
- state.mode = BAD;
- break top;
- }
- break; // need to emulate goto via "continue"
- }
- } while (_in < last && _out < end);
- /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
- len = bits >> 3;
- _in -= len;
- bits -= len << 3;
- hold &= (1 << bits) - 1;
- /* update state and return */
- strm.next_in = _in;
- strm.next_out = _out;
- strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
- strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
- state.hold = hold;
- state.bits = bits;
- return;
- };
- },{}],41:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- var utils = require('../utils/common');
- var adler32 = require('./adler32');
- var crc32 = require('./crc32');
- var inflate_fast = require('./inffast');
- var inflate_table = require('./inftrees');
- var CODES = 0;
- var LENS = 1;
- var DISTS = 2;
- /* Public constants ==========================================================*/
- /* ===========================================================================*/
- /* Allowed flush values; see deflate() and inflate() below for details */
- //var Z_NO_FLUSH = 0;
- //var Z_PARTIAL_FLUSH = 1;
- //var Z_SYNC_FLUSH = 2;
- //var Z_FULL_FLUSH = 3;
- var Z_FINISH = 4;
- var Z_BLOCK = 5;
- var Z_TREES = 6;
- /* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
- var Z_OK = 0;
- var Z_STREAM_END = 1;
- var Z_NEED_DICT = 2;
- //var Z_ERRNO = -1;
- var Z_STREAM_ERROR = -2;
- var Z_DATA_ERROR = -3;
- var Z_MEM_ERROR = -4;
- var Z_BUF_ERROR = -5;
- //var Z_VERSION_ERROR = -6;
- /* The deflate compression method */
- var Z_DEFLATED = 8;
- /* STATES ====================================================================*/
- /* ===========================================================================*/
- var HEAD = 1; /* i: waiting for magic header */
- var FLAGS = 2; /* i: waiting for method and flags (gzip) */
- var TIME = 3; /* i: waiting for modification time (gzip) */
- var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
- var EXLEN = 5; /* i: waiting for extra length (gzip) */
- var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
- var NAME = 7; /* i: waiting for end of file name (gzip) */
- var COMMENT = 8; /* i: waiting for end of comment (gzip) */
- var HCRC = 9; /* i: waiting for header crc (gzip) */
- var DICTID = 10; /* i: waiting for dictionary check value */
- var DICT = 11; /* waiting for inflateSetDictionary() call */
- var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
- var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
- var STORED = 14; /* i: waiting for stored size (length and complement) */
- var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
- var COPY = 16; /* i/o: waiting for input or output to copy stored block */
- var TABLE = 17; /* i: waiting for dynamic block table lengths */
- var LENLENS = 18; /* i: waiting for code length code lengths */
- var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
- var LEN_ = 20; /* i: same as LEN below, but only first time in */
- var LEN = 21; /* i: waiting for length/lit/eob code */
- var LENEXT = 22; /* i: waiting for length extra bits */
- var DIST = 23; /* i: waiting for distance code */
- var DISTEXT = 24; /* i: waiting for distance extra bits */
- var MATCH = 25; /* o: waiting for output space to copy string */
- var LIT = 26; /* o: waiting for output space to write literal */
- var CHECK = 27; /* i: waiting for 32-bit check value */
- var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
- var DONE = 29; /* finished check, done -- remain here until reset */
- var BAD = 30; /* got a data error -- remain here until reset */
- var MEM = 31; /* got an inflate() memory error -- remain here until reset */
- var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
- /* ===========================================================================*/
- var ENOUGH_LENS = 852;
- var ENOUGH_DISTS = 592;
- //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
- var MAX_WBITS = 15;
- /* 32K LZ77 window */
- var DEF_WBITS = MAX_WBITS;
- function zswap32(q) {
- return (((q >>> 24) & 0xff) +
- ((q >>> 8) & 0xff00) +
- ((q & 0xff00) << 8) +
- ((q & 0xff) << 24));
- }
- function InflateState() {
- this.mode = 0; /* current inflate mode */
- this.last = false; /* true if processing last block */
- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
- this.havedict = false; /* true if dictionary provided */
- this.flags = 0; /* gzip header method and flags (0 if zlib) */
- this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
- this.check = 0; /* protected copy of check value */
- this.total = 0; /* protected copy of output count */
- // TODO: may be {}
- this.head = null; /* where to save gzip header information */
- /* sliding window */
- this.wbits = 0; /* log base 2 of requested window size */
- this.wsize = 0; /* window size or zero if not using window */
- this.whave = 0; /* valid bytes in the window */
- this.wnext = 0; /* window write index */
- this.window = null; /* allocated sliding window, if needed */
- /* bit accumulator */
- this.hold = 0; /* input bit accumulator */
- this.bits = 0; /* number of bits in "in" */
- /* for string and stored block copying */
- this.length = 0; /* literal or length of data to copy */
- this.offset = 0; /* distance back to copy string from */
- /* for table and code decoding */
- this.extra = 0; /* extra bits needed */
- /* fixed and dynamic code tables */
- this.lencode = null; /* starting table for length/literal codes */
- this.distcode = null; /* starting table for distance codes */
- this.lenbits = 0; /* index bits for lencode */
- this.distbits = 0; /* index bits for distcode */
- /* dynamic table building */
- this.ncode = 0; /* number of code length code lengths */
- this.nlen = 0; /* number of length code lengths */
- this.ndist = 0; /* number of distance code lengths */
- this.have = 0; /* number of code lengths in lens[] */
- this.next = null; /* next available space in codes[] */
- this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
- this.work = new utils.Buf16(288); /* work area for code table building */
- /*
- because we don't have pointers in js, we use lencode and distcode directly
- as buffers so we don't need codes
- */
- //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
- this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
- this.distdyn = null; /* dynamic table for distance codes (JS specific) */
- this.sane = 0; /* if false, allow invalid distance too far */
- this.back = 0; /* bits back of last unprocessed length/lit */
- this.was = 0; /* initial length of match */
- }
- function inflateResetKeep(strm) {
- var state;
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- strm.total_in = strm.total_out = state.total = 0;
- strm.msg = ''; /*Z_NULL*/
- if (state.wrap) { /* to support ill-conceived Java test suite */
- strm.adler = state.wrap & 1;
- }
- state.mode = HEAD;
- state.last = 0;
- state.havedict = 0;
- state.dmax = 32768;
- state.head = null/*Z_NULL*/;
- state.hold = 0;
- state.bits = 0;
- //state.lencode = state.distcode = state.next = state.codes;
- state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
- state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
- state.sane = 1;
- state.back = -1;
- //Tracev((stderr, "inflate: reset\n"));
- return Z_OK;
- }
- function inflateReset(strm) {
- var state;
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- state.wsize = 0;
- state.whave = 0;
- state.wnext = 0;
- return inflateResetKeep(strm);
- }
- function inflateReset2(strm, windowBits) {
- var wrap;
- var state;
- /* get the state */
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- /* extract wrap request from windowBits parameter */
- if (windowBits < 0) {
- wrap = 0;
- windowBits = -windowBits;
- }
- else {
- wrap = (windowBits >> 4) + 1;
- if (windowBits < 48) {
- windowBits &= 15;
- }
- }
- /* set number of window bits, free window if different */
- if (windowBits && (windowBits < 8 || windowBits > 15)) {
- return Z_STREAM_ERROR;
- }
- if (state.window !== null && state.wbits !== windowBits) {
- state.window = null;
- }
- /* update state and reset the rest of it */
- state.wrap = wrap;
- state.wbits = windowBits;
- return inflateReset(strm);
- }
- function inflateInit2(strm, windowBits) {
- var ret;
- var state;
- if (!strm) { return Z_STREAM_ERROR; }
- //strm.msg = Z_NULL; /* in case we return an error */
- state = new InflateState();
- //if (state === Z_NULL) return Z_MEM_ERROR;
- //Tracev((stderr, "inflate: allocated\n"));
- strm.state = state;
- state.window = null/*Z_NULL*/;
- ret = inflateReset2(strm, windowBits);
- if (ret !== Z_OK) {
- strm.state = null/*Z_NULL*/;
- }
- return ret;
- }
- function inflateInit(strm) {
- return inflateInit2(strm, DEF_WBITS);
- }
- /*
- Return state with length and distance decoding tables and index sizes set to
- fixed code decoding. Normally this returns fixed tables from inffixed.h.
- If BUILDFIXED is defined, then instead this routine builds the tables the
- first time it's called, and returns those tables the first time and
- thereafter. This reduces the size of the code by about 2K bytes, in
- exchange for a little execution time. However, BUILDFIXED should not be
- used for threaded applications, since the rewriting of the tables and virgin
- may not be thread-safe.
- */
- var virgin = true;
- var lenfix, distfix; // We have no pointers in JS, so keep tables separate
- function fixedtables(state) {
- /* build fixed huffman tables if first call (may not be thread safe) */
- if (virgin) {
- var sym;
- lenfix = new utils.Buf32(512);
- distfix = new utils.Buf32(32);
- /* literal/length table */
- sym = 0;
- while (sym < 144) { state.lens[sym++] = 8; }
- while (sym < 256) { state.lens[sym++] = 9; }
- while (sym < 280) { state.lens[sym++] = 7; }
- while (sym < 288) { state.lens[sym++] = 8; }
- inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
- /* distance table */
- sym = 0;
- while (sym < 32) { state.lens[sym++] = 5; }
- inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
- /* do this just once */
- virgin = false;
- }
- state.lencode = lenfix;
- state.lenbits = 9;
- state.distcode = distfix;
- state.distbits = 5;
- }
- /*
- Update the window with the last wsize (normally 32K) bytes written before
- returning. If window does not exist yet, create it. This is only called
- when a window is already in use, or when output has been written during this
- inflate call, but the end of the deflate stream has not been reached yet.
- It is also called to create a window for dictionary data when a dictionary
- is loaded.
- Providing output buffers larger than 32K to inflate() should provide a speed
- advantage, since only the last 32K of output is copied to the sliding window
- upon return from inflate(), and since all distances after the first 32K of
- output will fall in the output data, making match copies simpler and faster.
- The advantage may be dependent on the size of the processor's data caches.
- */
- function updatewindow(strm, src, end, copy) {
- var dist;
- var state = strm.state;
- /* if it hasn't been done already, allocate space for the window */
- if (state.window === null) {
- state.wsize = 1 << state.wbits;
- state.wnext = 0;
- state.whave = 0;
- state.window = new utils.Buf8(state.wsize);
- }
- /* copy state->wsize or less output bytes into the circular window */
- if (copy >= state.wsize) {
- utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
- state.wnext = 0;
- state.whave = state.wsize;
- }
- else {
- dist = state.wsize - state.wnext;
- if (dist > copy) {
- dist = copy;
- }
- //zmemcpy(state->window + state->wnext, end - copy, dist);
- utils.arraySet(state.window, src, end - copy, dist, state.wnext);
- copy -= dist;
- if (copy) {
- //zmemcpy(state->window, end - copy, copy);
- utils.arraySet(state.window, src, end - copy, copy, 0);
- state.wnext = copy;
- state.whave = state.wsize;
- }
- else {
- state.wnext += dist;
- if (state.wnext === state.wsize) { state.wnext = 0; }
- if (state.whave < state.wsize) { state.whave += dist; }
- }
- }
- return 0;
- }
- function inflate(strm, flush) {
- var state;
- var input, output; // input/output buffers
- var next; /* next input INDEX */
- var put; /* next output INDEX */
- var have, left; /* available input and output */
- var hold; /* bit buffer */
- var bits; /* bits in bit buffer */
- var _in, _out; /* save starting available input and output */
- var copy; /* number of stored or match bytes to copy */
- var from; /* where to copy match bytes from */
- var from_source;
- var here = 0; /* current decoding table entry */
- var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
- //var last; /* parent table entry */
- var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
- var len; /* length to copy for repeats, bits to drop */
- var ret; /* return code */
- var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
- var opts;
- var n; // temporary var for NEED_BITS
- var order = /* permutation of code lengths */
- [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
- if (!strm || !strm.state || !strm.output ||
- (!strm.input && strm.avail_in !== 0)) {
- return Z_STREAM_ERROR;
- }
- state = strm.state;
- if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
- //--- LOAD() ---
- put = strm.next_out;
- output = strm.output;
- left = strm.avail_out;
- next = strm.next_in;
- input = strm.input;
- have = strm.avail_in;
- hold = state.hold;
- bits = state.bits;
- //---
- _in = have;
- _out = left;
- ret = Z_OK;
- inf_leave: // goto emulation
- for (;;) {
- switch (state.mode) {
- case HEAD:
- if (state.wrap === 0) {
- state.mode = TYPEDO;
- break;
- }
- //=== NEEDBITS(16);
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
- state.check = 0/*crc32(0L, Z_NULL, 0)*/;
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = FLAGS;
- break;
- }
- state.flags = 0; /* expect zlib header */
- if (state.head) {
- state.head.done = false;
- }
- if (!(state.wrap & 1) || /* check if zlib header allowed */
- (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
- strm.msg = 'incorrect header check';
- state.mode = BAD;
- break;
- }
- if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
- strm.msg = 'unknown compression method';
- state.mode = BAD;
- break;
- }
- //--- DROPBITS(4) ---//
- hold >>>= 4;
- bits -= 4;
- //---//
- len = (hold & 0x0f)/*BITS(4)*/ + 8;
- if (state.wbits === 0) {
- state.wbits = len;
- }
- else if (len > state.wbits) {
- strm.msg = 'invalid window size';
- state.mode = BAD;
- break;
- }
- state.dmax = 1 << len;
- //Tracev((stderr, "inflate: zlib header ok\n"));
- strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
- state.mode = hold & 0x200 ? DICTID : TYPE;
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- break;
- case FLAGS:
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.flags = hold;
- if ((state.flags & 0xff) !== Z_DEFLATED) {
- strm.msg = 'unknown compression method';
- state.mode = BAD;
- break;
- }
- if (state.flags & 0xe000) {
- strm.msg = 'unknown header flags set';
- state.mode = BAD;
- break;
- }
- if (state.head) {
- state.head.text = ((hold >> 8) & 1);
- }
- if (state.flags & 0x0200) {
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = TIME;
- /* falls through */
- case TIME:
- //=== NEEDBITS(32); */
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (state.head) {
- state.head.time = hold;
- }
- if (state.flags & 0x0200) {
- //=== CRC4(state.check, hold)
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- hbuf[2] = (hold >>> 16) & 0xff;
- hbuf[3] = (hold >>> 24) & 0xff;
- state.check = crc32(state.check, hbuf, 4, 0);
- //===
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = OS;
- /* falls through */
- case OS:
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (state.head) {
- state.head.xflags = (hold & 0xff);
- state.head.os = (hold >> 8);
- }
- if (state.flags & 0x0200) {
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = EXLEN;
- /* falls through */
- case EXLEN:
- if (state.flags & 0x0400) {
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.length = hold;
- if (state.head) {
- state.head.extra_len = hold;
- }
- if (state.flags & 0x0200) {
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- }
- else if (state.head) {
- state.head.extra = null/*Z_NULL*/;
- }
- state.mode = EXTRA;
- /* falls through */
- case EXTRA:
- if (state.flags & 0x0400) {
- copy = state.length;
- if (copy > have) { copy = have; }
- if (copy) {
- if (state.head) {
- len = state.head.extra_len - state.length;
- if (!state.head.extra) {
- // Use untyped array for more convenient processing later
- state.head.extra = new Array(state.head.extra_len);
- }
- utils.arraySet(
- state.head.extra,
- input,
- next,
- // extra field is limited to 65536 bytes
- // - no need for additional size check
- copy,
- /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
- len
- );
- //zmemcpy(state.head.extra + len, next,
- // len + copy > state.head.extra_max ?
- // state.head.extra_max - len : copy);
- }
- if (state.flags & 0x0200) {
- state.check = crc32(state.check, input, copy, next);
- }
- have -= copy;
- next += copy;
- state.length -= copy;
- }
- if (state.length) { break inf_leave; }
- }
- state.length = 0;
- state.mode = NAME;
- /* falls through */
- case NAME:
- if (state.flags & 0x0800) {
- if (have === 0) { break inf_leave; }
- copy = 0;
- do {
- // TODO: 2 or 1 bytes?
- len = input[next + copy++];
- /* use constant limit because in js we should not preallocate memory */
- if (state.head && len &&
- (state.length < 65536 /*state.head.name_max*/)) {
- state.head.name += String.fromCharCode(len);
- }
- } while (len && copy < have);
- if (state.flags & 0x0200) {
- state.check = crc32(state.check, input, copy, next);
- }
- have -= copy;
- next += copy;
- if (len) { break inf_leave; }
- }
- else if (state.head) {
- state.head.name = null;
- }
- state.length = 0;
- state.mode = COMMENT;
- /* falls through */
- case COMMENT:
- if (state.flags & 0x1000) {
- if (have === 0) { break inf_leave; }
- copy = 0;
- do {
- len = input[next + copy++];
- /* use constant limit because in js we should not preallocate memory */
- if (state.head && len &&
- (state.length < 65536 /*state.head.comm_max*/)) {
- state.head.comment += String.fromCharCode(len);
- }
- } while (len && copy < have);
- if (state.flags & 0x0200) {
- state.check = crc32(state.check, input, copy, next);
- }
- have -= copy;
- next += copy;
- if (len) { break inf_leave; }
- }
- else if (state.head) {
- state.head.comment = null;
- }
- state.mode = HCRC;
- /* falls through */
- case HCRC:
- if (state.flags & 0x0200) {
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (hold !== (state.check & 0xffff)) {
- strm.msg = 'header crc mismatch';
- state.mode = BAD;
- break;
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- }
- if (state.head) {
- state.head.hcrc = ((state.flags >> 9) & 1);
- state.head.done = true;
- }
- strm.adler = state.check = 0;
- state.mode = TYPE;
- break;
- case DICTID:
- //=== NEEDBITS(32); */
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- strm.adler = state.check = zswap32(hold);
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = DICT;
- /* falls through */
- case DICT:
- if (state.havedict === 0) {
- //--- RESTORE() ---
- strm.next_out = put;
- strm.avail_out = left;
- strm.next_in = next;
- strm.avail_in = have;
- state.hold = hold;
- state.bits = bits;
- //---
- return Z_NEED_DICT;
- }
- strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
- state.mode = TYPE;
- /* falls through */
- case TYPE:
- if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
- /* falls through */
- case TYPEDO:
- if (state.last) {
- //--- BYTEBITS() ---//
- hold >>>= bits & 7;
- bits -= bits & 7;
- //---//
- state.mode = CHECK;
- break;
- }
- //=== NEEDBITS(3); */
- while (bits < 3) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.last = (hold & 0x01)/*BITS(1)*/;
- //--- DROPBITS(1) ---//
- hold >>>= 1;
- bits -= 1;
- //---//
- switch ((hold & 0x03)/*BITS(2)*/) {
- case 0: /* stored block */
- //Tracev((stderr, "inflate: stored block%s\n",
- // state.last ? " (last)" : ""));
- state.mode = STORED;
- break;
- case 1: /* fixed block */
- fixedtables(state);
- //Tracev((stderr, "inflate: fixed codes block%s\n",
- // state.last ? " (last)" : ""));
- state.mode = LEN_; /* decode codes */
- if (flush === Z_TREES) {
- //--- DROPBITS(2) ---//
- hold >>>= 2;
- bits -= 2;
- //---//
- break inf_leave;
- }
- break;
- case 2: /* dynamic block */
- //Tracev((stderr, "inflate: dynamic codes block%s\n",
- // state.last ? " (last)" : ""));
- state.mode = TABLE;
- break;
- case 3:
- strm.msg = 'invalid block type';
- state.mode = BAD;
- }
- //--- DROPBITS(2) ---//
- hold >>>= 2;
- bits -= 2;
- //---//
- break;
- case STORED:
- //--- BYTEBITS() ---// /* go to byte boundary */
- hold >>>= bits & 7;
- bits -= bits & 7;
- //---//
- //=== NEEDBITS(32); */
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
- strm.msg = 'invalid stored block lengths';
- state.mode = BAD;
- break;
- }
- state.length = hold & 0xffff;
- //Tracev((stderr, "inflate: stored length %u\n",
- // state.length));
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = COPY_;
- if (flush === Z_TREES) { break inf_leave; }
- /* falls through */
- case COPY_:
- state.mode = COPY;
- /* falls through */
- case COPY:
- copy = state.length;
- if (copy) {
- if (copy > have) { copy = have; }
- if (copy > left) { copy = left; }
- if (copy === 0) { break inf_leave; }
- //--- zmemcpy(put, next, copy); ---
- utils.arraySet(output, input, next, copy, put);
- //---//
- have -= copy;
- next += copy;
- left -= copy;
- put += copy;
- state.length -= copy;
- break;
- }
- //Tracev((stderr, "inflate: stored end\n"));
- state.mode = TYPE;
- break;
- case TABLE:
- //=== NEEDBITS(14); */
- while (bits < 14) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
- //--- DROPBITS(5) ---//
- hold >>>= 5;
- bits -= 5;
- //---//
- state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
- //--- DROPBITS(5) ---//
- hold >>>= 5;
- bits -= 5;
- //---//
- state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
- //--- DROPBITS(4) ---//
- hold >>>= 4;
- bits -= 4;
- //---//
- //#ifndef PKZIP_BUG_WORKAROUND
- if (state.nlen > 286 || state.ndist > 30) {
- strm.msg = 'too many length or distance symbols';
- state.mode = BAD;
- break;
- }
- //#endif
- //Tracev((stderr, "inflate: table sizes ok\n"));
- state.have = 0;
- state.mode = LENLENS;
- /* falls through */
- case LENLENS:
- while (state.have < state.ncode) {
- //=== NEEDBITS(3);
- while (bits < 3) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
- //--- DROPBITS(3) ---//
- hold >>>= 3;
- bits -= 3;
- //---//
- }
- while (state.have < 19) {
- state.lens[order[state.have++]] = 0;
- }
- // We have separate tables & no pointers. 2 commented lines below not needed.
- //state.next = state.codes;
- //state.lencode = state.next;
- // Switch to use dynamic table
- state.lencode = state.lendyn;
- state.lenbits = 7;
- opts = { bits: state.lenbits };
- ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
- state.lenbits = opts.bits;
- if (ret) {
- strm.msg = 'invalid code lengths set';
- state.mode = BAD;
- break;
- }
- //Tracev((stderr, "inflate: code lengths ok\n"));
- state.have = 0;
- state.mode = CODELENS;
- /* falls through */
- case CODELENS:
- while (state.have < state.nlen + state.ndist) {
- for (;;) {
- here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
- if ((here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- if (here_val < 16) {
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- state.lens[state.have++] = here_val;
- }
- else {
- if (here_val === 16) {
- //=== NEEDBITS(here.bits + 2);
- n = here_bits + 2;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- if (state.have === 0) {
- strm.msg = 'invalid bit length repeat';
- state.mode = BAD;
- break;
- }
- len = state.lens[state.have - 1];
- copy = 3 + (hold & 0x03);//BITS(2);
- //--- DROPBITS(2) ---//
- hold >>>= 2;
- bits -= 2;
- //---//
- }
- else if (here_val === 17) {
- //=== NEEDBITS(here.bits + 3);
- n = here_bits + 3;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- len = 0;
- copy = 3 + (hold & 0x07);//BITS(3);
- //--- DROPBITS(3) ---//
- hold >>>= 3;
- bits -= 3;
- //---//
- }
- else {
- //=== NEEDBITS(here.bits + 7);
- n = here_bits + 7;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- len = 0;
- copy = 11 + (hold & 0x7f);//BITS(7);
- //--- DROPBITS(7) ---//
- hold >>>= 7;
- bits -= 7;
- //---//
- }
- if (state.have + copy > state.nlen + state.ndist) {
- strm.msg = 'invalid bit length repeat';
- state.mode = BAD;
- break;
- }
- while (copy--) {
- state.lens[state.have++] = len;
- }
- }
- }
- /* handle error breaks in while */
- if (state.mode === BAD) { break; }
- /* check for end-of-block code (better have one) */
- if (state.lens[256] === 0) {
- strm.msg = 'invalid code -- missing end-of-block';
- state.mode = BAD;
- break;
- }
- /* build code tables -- note: do not change the lenbits or distbits
- values here (9 and 6) without reading the comments in inftrees.h
- concerning the ENOUGH constants, which depend on those values */
- state.lenbits = 9;
- opts = { bits: state.lenbits };
- ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
- // We have separate tables & no pointers. 2 commented lines below not needed.
- // state.next_index = opts.table_index;
- state.lenbits = opts.bits;
- // state.lencode = state.next;
- if (ret) {
- strm.msg = 'invalid literal/lengths set';
- state.mode = BAD;
- break;
- }
- state.distbits = 6;
- //state.distcode.copy(state.codes);
- // Switch to use dynamic table
- state.distcode = state.distdyn;
- opts = { bits: state.distbits };
- ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
- // We have separate tables & no pointers. 2 commented lines below not needed.
- // state.next_index = opts.table_index;
- state.distbits = opts.bits;
- // state.distcode = state.next;
- if (ret) {
- strm.msg = 'invalid distances set';
- state.mode = BAD;
- break;
- }
- //Tracev((stderr, 'inflate: codes ok\n'));
- state.mode = LEN_;
- if (flush === Z_TREES) { break inf_leave; }
- /* falls through */
- case LEN_:
- state.mode = LEN;
- /* falls through */
- case LEN:
- if (have >= 6 && left >= 258) {
- //--- RESTORE() ---
- strm.next_out = put;
- strm.avail_out = left;
- strm.next_in = next;
- strm.avail_in = have;
- state.hold = hold;
- state.bits = bits;
- //---
- inflate_fast(strm, _out);
- //--- LOAD() ---
- put = strm.next_out;
- output = strm.output;
- left = strm.avail_out;
- next = strm.next_in;
- input = strm.input;
- have = strm.avail_in;
- hold = state.hold;
- bits = state.bits;
- //---
- if (state.mode === TYPE) {
- state.back = -1;
- }
- break;
- }
- state.back = 0;
- for (;;) {
- here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
- if (here_bits <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- if (here_op && (here_op & 0xf0) === 0) {
- last_bits = here_bits;
- last_op = here_op;
- last_val = here_val;
- for (;;) {
- here = state.lencode[last_val +
- ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
- if ((last_bits + here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- //--- DROPBITS(last.bits) ---//
- hold >>>= last_bits;
- bits -= last_bits;
- //---//
- state.back += last_bits;
- }
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- state.back += here_bits;
- state.length = here_val;
- if (here_op === 0) {
- //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
- // "inflate: literal '%c'\n" :
- // "inflate: literal 0x%02x\n", here.val));
- state.mode = LIT;
- break;
- }
- if (here_op & 32) {
- //Tracevv((stderr, "inflate: end of block\n"));
- state.back = -1;
- state.mode = TYPE;
- break;
- }
- if (here_op & 64) {
- strm.msg = 'invalid literal/length code';
- state.mode = BAD;
- break;
- }
- state.extra = here_op & 15;
- state.mode = LENEXT;
- /* falls through */
- case LENEXT:
- if (state.extra) {
- //=== NEEDBITS(state.extra);
- n = state.extra;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
- //--- DROPBITS(state.extra) ---//
- hold >>>= state.extra;
- bits -= state.extra;
- //---//
- state.back += state.extra;
- }
- //Tracevv((stderr, "inflate: length %u\n", state.length));
- state.was = state.length;
- state.mode = DIST;
- /* falls through */
- case DIST:
- for (;;) {
- here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
- if ((here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- if ((here_op & 0xf0) === 0) {
- last_bits = here_bits;
- last_op = here_op;
- last_val = here_val;
- for (;;) {
- here = state.distcode[last_val +
- ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
- if ((last_bits + here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- //--- DROPBITS(last.bits) ---//
- hold >>>= last_bits;
- bits -= last_bits;
- //---//
- state.back += last_bits;
- }
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- state.back += here_bits;
- if (here_op & 64) {
- strm.msg = 'invalid distance code';
- state.mode = BAD;
- break;
- }
- state.offset = here_val;
- state.extra = (here_op) & 15;
- state.mode = DISTEXT;
- /* falls through */
- case DISTEXT:
- if (state.extra) {
- //=== NEEDBITS(state.extra);
- n = state.extra;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
- //--- DROPBITS(state.extra) ---//
- hold >>>= state.extra;
- bits -= state.extra;
- //---//
- state.back += state.extra;
- }
- //#ifdef INFLATE_STRICT
- if (state.offset > state.dmax) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break;
- }
- //#endif
- //Tracevv((stderr, "inflate: distance %u\n", state.offset));
- state.mode = MATCH;
- /* falls through */
- case MATCH:
- if (left === 0) { break inf_leave; }
- copy = _out - left;
- if (state.offset > copy) { /* copy from window */
- copy = state.offset - copy;
- if (copy > state.whave) {
- if (state.sane) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break;
- }
- // (!) This block is disabled in zlib defaults,
- // don't enable it for binary compatibility
- //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
- // Trace((stderr, "inflate.c too far\n"));
- // copy -= state.whave;
- // if (copy > state.length) { copy = state.length; }
- // if (copy > left) { copy = left; }
- // left -= copy;
- // state.length -= copy;
- // do {
- // output[put++] = 0;
- // } while (--copy);
- // if (state.length === 0) { state.mode = LEN; }
- // break;
- //#endif
- }
- if (copy > state.wnext) {
- copy -= state.wnext;
- from = state.wsize - copy;
- }
- else {
- from = state.wnext - copy;
- }
- if (copy > state.length) { copy = state.length; }
- from_source = state.window;
- }
- else { /* copy from output */
- from_source = output;
- from = put - state.offset;
- copy = state.length;
- }
- if (copy > left) { copy = left; }
- left -= copy;
- state.length -= copy;
- do {
- output[put++] = from_source[from++];
- } while (--copy);
- if (state.length === 0) { state.mode = LEN; }
- break;
- case LIT:
- if (left === 0) { break inf_leave; }
- output[put++] = state.length;
- left--;
- state.mode = LEN;
- break;
- case CHECK:
- if (state.wrap) {
- //=== NEEDBITS(32);
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- // Use '|' instead of '+' to make sure that result is signed
- hold |= input[next++] << bits;
- bits += 8;
- }
- //===//
- _out -= left;
- strm.total_out += _out;
- state.total += _out;
- if (_out) {
- strm.adler = state.check =
- /*UPDATE(state.check, put - _out, _out);*/
- (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
- }
- _out = left;
- // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
- if ((state.flags ? hold : zswap32(hold)) !== state.check) {
- strm.msg = 'incorrect data check';
- state.mode = BAD;
- break;
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- //Tracev((stderr, "inflate: check matches trailer\n"));
- }
- state.mode = LENGTH;
- /* falls through */
- case LENGTH:
- if (state.wrap && state.flags) {
- //=== NEEDBITS(32);
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (hold !== (state.total & 0xffffffff)) {
- strm.msg = 'incorrect length check';
- state.mode = BAD;
- break;
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- //Tracev((stderr, "inflate: length matches trailer\n"));
- }
- state.mode = DONE;
- /* falls through */
- case DONE:
- ret = Z_STREAM_END;
- break inf_leave;
- case BAD:
- ret = Z_DATA_ERROR;
- break inf_leave;
- case MEM:
- return Z_MEM_ERROR;
- case SYNC:
- /* falls through */
- default:
- return Z_STREAM_ERROR;
- }
- }
- // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
- /*
- Return from inflate(), updating the total counts and the check value.
- If there was no progress during the inflate() call, return a buffer
- error. Call updatewindow() to create and/or update the window state.
- Note: a memory error from inflate() is non-recoverable.
- */
- //--- RESTORE() ---
- strm.next_out = put;
- strm.avail_out = left;
- strm.next_in = next;
- strm.avail_in = have;
- state.hold = hold;
- state.bits = bits;
- //---
- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
- (state.mode < CHECK || flush !== Z_FINISH))) {
- if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
- state.mode = MEM;
- return Z_MEM_ERROR;
- }
- }
- _in -= strm.avail_in;
- _out -= strm.avail_out;
- strm.total_in += _in;
- strm.total_out += _out;
- state.total += _out;
- if (state.wrap && _out) {
- strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
- (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
- }
- strm.data_type = state.bits + (state.last ? 64 : 0) +
- (state.mode === TYPE ? 128 : 0) +
- (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
- if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
- ret = Z_BUF_ERROR;
- }
- return ret;
- }
- function inflateEnd(strm) {
- if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
- return Z_STREAM_ERROR;
- }
- var state = strm.state;
- if (state.window) {
- state.window = null;
- }
- strm.state = null;
- return Z_OK;
- }
- function inflateGetHeader(strm, head) {
- var state;
- /* check state */
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
- /* save header structure */
- state.head = head;
- head.done = false;
- return Z_OK;
- }
- function inflateSetDictionary(strm, dictionary) {
- var dictLength = dictionary.length;
- var state;
- var dictid;
- var ret;
- /* check state */
- if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
- state = strm.state;
- if (state.wrap !== 0 && state.mode !== DICT) {
- return Z_STREAM_ERROR;
- }
- /* check for correct dictionary identifier */
- if (state.mode === DICT) {
- dictid = 1; /* adler32(0, null, 0)*/
- /* dictid = adler32(dictid, dictionary, dictLength); */
- dictid = adler32(dictid, dictionary, dictLength, 0);
- if (dictid !== state.check) {
- return Z_DATA_ERROR;
- }
- }
- /* copy dictionary to window using updatewindow(), which will amend the
- existing dictionary if appropriate */
- ret = updatewindow(strm, dictionary, dictLength, dictLength);
- if (ret) {
- state.mode = MEM;
- return Z_MEM_ERROR;
- }
- state.havedict = 1;
- // Tracev((stderr, "inflate: dictionary set\n"));
- return Z_OK;
- }
- exports.inflateReset = inflateReset;
- exports.inflateReset2 = inflateReset2;
- exports.inflateResetKeep = inflateResetKeep;
- exports.inflateInit = inflateInit;
- exports.inflateInit2 = inflateInit2;
- exports.inflate = inflate;
- exports.inflateEnd = inflateEnd;
- exports.inflateGetHeader = inflateGetHeader;
- exports.inflateSetDictionary = inflateSetDictionary;
- exports.inflateInfo = 'pako inflate (from Nodeca project)';
- /* Not implemented
- exports.inflateCopy = inflateCopy;
- exports.inflateGetDictionary = inflateGetDictionary;
- exports.inflateMark = inflateMark;
- exports.inflatePrime = inflatePrime;
- exports.inflateSync = inflateSync;
- exports.inflateSyncPoint = inflateSyncPoint;
- exports.inflateUndermine = inflateUndermine;
- */
- },{"../utils/common":35,"./adler32":36,"./crc32":38,"./inffast":40,"./inftrees":42}],42:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- var utils = require('../utils/common');
- var MAXBITS = 15;
- var ENOUGH_LENS = 852;
- var ENOUGH_DISTS = 592;
- //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
- var CODES = 0;
- var LENS = 1;
- var DISTS = 2;
- var lbase = [ /* Length codes 257..285 base */
- 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
- 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
- ];
- var lext = [ /* Length codes 257..285 extra */
- 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
- 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
- ];
- var dbase = [ /* Distance codes 0..29 base */
- 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
- 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
- 8193, 12289, 16385, 24577, 0, 0
- ];
- var dext = [ /* Distance codes 0..29 extra */
- 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
- 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
- 28, 28, 29, 29, 64, 64
- ];
- module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
- {
- var bits = opts.bits;
- //here = opts.here; /* table entry for duplication */
- var len = 0; /* a code's length in bits */
- var sym = 0; /* index of code symbols */
- var min = 0, max = 0; /* minimum and maximum code lengths */
- var root = 0; /* number of index bits for root table */
- var curr = 0; /* number of index bits for current table */
- var drop = 0; /* code bits to drop for sub-table */
- var left = 0; /* number of prefix codes available */
- var used = 0; /* code entries in table used */
- var huff = 0; /* Huffman code */
- var incr; /* for incrementing code, index */
- var fill; /* index for replicating entries */
- var low; /* low bits for current root entry */
- var mask; /* mask for low root bits */
- var next; /* next available space in table */
- var base = null; /* base value table to use */
- var base_index = 0;
- // var shoextra; /* extra bits table to use */
- var end; /* use base and extra for symbol > end */
- var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
- var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
- var extra = null;
- var extra_index = 0;
- var here_bits, here_op, here_val;
- /*
- Process a set of code lengths to create a canonical Huffman code. The
- code lengths are lens[0..codes-1]. Each length corresponds to the
- symbols 0..codes-1. The Huffman code is generated by first sorting the
- symbols by length from short to long, and retaining the symbol order
- for codes with equal lengths. Then the code starts with all zero bits
- for the first code of the shortest length, and the codes are integer
- increments for the same length, and zeros are appended as the length
- increases. For the deflate format, these bits are stored backwards
- from their more natural integer increment ordering, and so when the
- decoding tables are built in the large loop below, the integer codes
- are incremented backwards.
- This routine assumes, but does not check, that all of the entries in
- lens[] are in the range 0..MAXBITS. The caller must assure this.
- 1..MAXBITS is interpreted as that code length. zero means that that
- symbol does not occur in this code.
- The codes are sorted by computing a count of codes for each length,
- creating from that a table of starting indices for each length in the
- sorted table, and then entering the symbols in order in the sorted
- table. The sorted table is work[], with that space being provided by
- the caller.
- The length counts are used for other purposes as well, i.e. finding
- the minimum and maximum length codes, determining if there are any
- codes at all, checking for a valid set of lengths, and looking ahead
- at length counts to determine sub-table sizes when building the
- decoding tables.
- */
- /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
- for (len = 0; len <= MAXBITS; len++) {
- count[len] = 0;
- }
- for (sym = 0; sym < codes; sym++) {
- count[lens[lens_index + sym]]++;
- }
- /* bound code lengths, force root to be within code lengths */
- root = bits;
- for (max = MAXBITS; max >= 1; max--) {
- if (count[max] !== 0) { break; }
- }
- if (root > max) {
- root = max;
- }
- if (max === 0) { /* no symbols to code at all */
- //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
- //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
- //table.val[opts.table_index++] = 0; //here.val = (var short)0;
- table[table_index++] = (1 << 24) | (64 << 16) | 0;
- //table.op[opts.table_index] = 64;
- //table.bits[opts.table_index] = 1;
- //table.val[opts.table_index++] = 0;
- table[table_index++] = (1 << 24) | (64 << 16) | 0;
- opts.bits = 1;
- return 0; /* no symbols, but wait for decoding to report error */
- }
- for (min = 1; min < max; min++) {
- if (count[min] !== 0) { break; }
- }
- if (root < min) {
- root = min;
- }
- /* check for an over-subscribed or incomplete set of lengths */
- left = 1;
- for (len = 1; len <= MAXBITS; len++) {
- left <<= 1;
- left -= count[len];
- if (left < 0) {
- return -1;
- } /* over-subscribed */
- }
- if (left > 0 && (type === CODES || max !== 1)) {
- return -1; /* incomplete set */
- }
- /* generate offsets into symbol table for each length for sorting */
- offs[1] = 0;
- for (len = 1; len < MAXBITS; len++) {
- offs[len + 1] = offs[len] + count[len];
- }
- /* sort symbols by length, by symbol order within each length */
- for (sym = 0; sym < codes; sym++) {
- if (lens[lens_index + sym] !== 0) {
- work[offs[lens[lens_index + sym]]++] = sym;
- }
- }
- /*
- Create and fill in decoding tables. In this loop, the table being
- filled is at next and has curr index bits. The code being used is huff
- with length len. That code is converted to an index by dropping drop
- bits off of the bottom. For codes where len is less than drop + curr,
- those top drop + curr - len bits are incremented through all values to
- fill the table with replicated entries.
- root is the number of index bits for the root table. When len exceeds
- root, sub-tables are created pointed to by the root entry with an index
- of the low root bits of huff. This is saved in low to check for when a
- new sub-table should be started. drop is zero when the root table is
- being filled, and drop is root when sub-tables are being filled.
- When a new sub-table is needed, it is necessary to look ahead in the
- code lengths to determine what size sub-table is needed. The length
- counts are used for this, and so count[] is decremented as codes are
- entered in the tables.
- used keeps track of how many table entries have been allocated from the
- provided *table space. It is checked for LENS and DIST tables against
- the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
- the initial root table size constants. See the comments in inftrees.h
- for more information.
- sym increments through all symbols, and the loop terminates when
- all codes of length max, i.e. all codes, have been processed. This
- routine permits incomplete codes, so another loop after this one fills
- in the rest of the decoding tables with invalid code markers.
- */
- /* set up for code type */
- // poor man optimization - use if-else instead of switch,
- // to avoid deopts in old v8
- if (type === CODES) {
- base = extra = work; /* dummy value--not used */
- end = 19;
- } else if (type === LENS) {
- base = lbase;
- base_index -= 257;
- extra = lext;
- extra_index -= 257;
- end = 256;
- } else { /* DISTS */
- base = dbase;
- extra = dext;
- end = -1;
- }
- /* initialize opts for loop */
- huff = 0; /* starting code */
- sym = 0; /* starting code symbol */
- len = min; /* starting code length */
- next = table_index; /* current table to fill in */
- curr = root; /* current table index bits */
- drop = 0; /* current bits to drop from code for index */
- low = -1; /* trigger new sub-table when len > root */
- used = 1 << root; /* use root table entries */
- mask = used - 1; /* mask for comparing low */
- /* check available table space */
- if ((type === LENS && used > ENOUGH_LENS) ||
- (type === DISTS && used > ENOUGH_DISTS)) {
- return 1;
- }
- /* process all codes and make table entries */
- for (;;) {
- /* create table entry */
- here_bits = len - drop;
- if (work[sym] < end) {
- here_op = 0;
- here_val = work[sym];
- }
- else if (work[sym] > end) {
- here_op = extra[extra_index + work[sym]];
- here_val = base[base_index + work[sym]];
- }
- else {
- here_op = 32 + 64; /* end of block */
- here_val = 0;
- }
- /* replicate for those indices with low len bits equal to huff */
- incr = 1 << (len - drop);
- fill = 1 << curr;
- min = fill; /* save offset to next table */
- do {
- fill -= incr;
- table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
- } while (fill !== 0);
- /* backwards increment the len-bit code huff */
- incr = 1 << (len - 1);
- while (huff & incr) {
- incr >>= 1;
- }
- if (incr !== 0) {
- huff &= incr - 1;
- huff += incr;
- } else {
- huff = 0;
- }
- /* go to next symbol, update count, len */
- sym++;
- if (--count[len] === 0) {
- if (len === max) { break; }
- len = lens[lens_index + work[sym]];
- }
- /* create new sub-table if needed */
- if (len > root && (huff & mask) !== low) {
- /* if first time, transition to sub-tables */
- if (drop === 0) {
- drop = root;
- }
- /* increment past last table */
- next += min; /* here min is 1 << curr */
- /* determine length of next table */
- curr = len - drop;
- left = 1 << curr;
- while (curr + drop < max) {
- left -= count[curr + drop];
- if (left <= 0) { break; }
- curr++;
- left <<= 1;
- }
- /* check for enough space */
- used += 1 << curr;
- if ((type === LENS && used > ENOUGH_LENS) ||
- (type === DISTS && used > ENOUGH_DISTS)) {
- return 1;
- }
- /* point entry in root table to sub-table */
- low = huff & mask;
- /*table.op[low] = curr;
- table.bits[low] = root;
- table.val[low] = next - opts.table_index;*/
- table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
- }
- }
- /* fill in remaining table entry if code is incomplete (guaranteed to have
- at most one remaining entry, since if the code is incomplete, the
- maximum code length that was allowed to get this far is one bit) */
- if (huff !== 0) {
- //table.op[next + huff] = 64; /* invalid code marker */
- //table.bits[next + huff] = len - drop;
- //table.val[next + huff] = 0;
- table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
- }
- /* set return parameters */
- //opts.table_index += used;
- opts.bits = root;
- return 0;
- };
- },{"../utils/common":35}],43:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- module.exports = {
- 2: 'need dictionary', /* Z_NEED_DICT 2 */
- 1: 'stream end', /* Z_STREAM_END 1 */
- 0: '', /* Z_OK 0 */
- '-1': 'file error', /* Z_ERRNO (-1) */
- '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
- '-3': 'data error', /* Z_DATA_ERROR (-3) */
- '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
- '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
- '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
- };
- },{}],44:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- /* eslint-disable space-unary-ops */
- var utils = require('../utils/common');
- /* Public constants ==========================================================*/
- /* ===========================================================================*/
- //var Z_FILTERED = 1;
- //var Z_HUFFMAN_ONLY = 2;
- //var Z_RLE = 3;
- var Z_FIXED = 4;
- //var Z_DEFAULT_STRATEGY = 0;
- /* Possible values of the data_type field (though see inflate()) */
- var Z_BINARY = 0;
- var Z_TEXT = 1;
- //var Z_ASCII = 1; // = Z_TEXT
- var Z_UNKNOWN = 2;
- /*============================================================================*/
- function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
- // From zutil.h
- var STORED_BLOCK = 0;
- var STATIC_TREES = 1;
- var DYN_TREES = 2;
- /* The three kinds of block type */
- var MIN_MATCH = 3;
- var MAX_MATCH = 258;
- /* The minimum and maximum match lengths */
- // From deflate.h
- /* ===========================================================================
- * Internal compression state.
- */
- var LENGTH_CODES = 29;
- /* number of length codes, not counting the special END_BLOCK code */
- var LITERALS = 256;
- /* number of literal bytes 0..255 */
- var L_CODES = LITERALS + 1 + LENGTH_CODES;
- /* number of Literal or Length codes, including the END_BLOCK code */
- var D_CODES = 30;
- /* number of distance codes */
- var BL_CODES = 19;
- /* number of codes used to transfer the bit lengths */
- var HEAP_SIZE = 2 * L_CODES + 1;
- /* maximum heap size */
- var MAX_BITS = 15;
- /* All codes must not exceed MAX_BITS bits */
- var Buf_size = 16;
- /* size of bit buffer in bi_buf */
- /* ===========================================================================
- * Constants
- */
- var MAX_BL_BITS = 7;
- /* Bit length codes must not exceed MAX_BL_BITS bits */
- var END_BLOCK = 256;
- /* end of block literal code */
- var REP_3_6 = 16;
- /* repeat previous bit length 3-6 times (2 bits of repeat count) */
- var REPZ_3_10 = 17;
- /* repeat a zero length 3-10 times (3 bits of repeat count) */
- var REPZ_11_138 = 18;
- /* repeat a zero length 11-138 times (7 bits of repeat count) */
- /* eslint-disable comma-spacing,array-bracket-spacing */
- var extra_lbits = /* extra bits for each length code */
- [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
- var extra_dbits = /* extra bits for each distance code */
- [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
- var extra_blbits = /* extra bits for each bit length code */
- [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
- var bl_order =
- [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
- /* eslint-enable comma-spacing,array-bracket-spacing */
- /* The lengths of the bit length codes are sent in order of decreasing
- * probability, to avoid transmitting the lengths for unused bit length codes.
- */
- /* ===========================================================================
- * Local data. These are initialized only once.
- */
- // We pre-fill arrays with 0 to avoid uninitialized gaps
- var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
- // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
- var static_ltree = new Array((L_CODES + 2) * 2);
- zero(static_ltree);
- /* The static literal tree. Since the bit lengths are imposed, there is no
- * need for the L_CODES extra codes used during heap construction. However
- * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
- * below).
- */
- var static_dtree = new Array(D_CODES * 2);
- zero(static_dtree);
- /* The static distance tree. (Actually a trivial tree since all codes use
- * 5 bits.)
- */
- var _dist_code = new Array(DIST_CODE_LEN);
- zero(_dist_code);
- /* Distance codes. The first 256 values correspond to the distances
- * 3 .. 258, the last 256 values correspond to the top 8 bits of
- * the 15 bit distances.
- */
- var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
- zero(_length_code);
- /* length code for each normalized match length (0 == MIN_MATCH) */
- var base_length = new Array(LENGTH_CODES);
- zero(base_length);
- /* First normalized length for each code (0 = MIN_MATCH) */
- var base_dist = new Array(D_CODES);
- zero(base_dist);
- /* First normalized distance for each code (0 = distance of 1) */
- function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
- this.static_tree = static_tree; /* static tree or NULL */
- this.extra_bits = extra_bits; /* extra bits for each code or NULL */
- this.extra_base = extra_base; /* base index for extra_bits */
- this.elems = elems; /* max number of elements in the tree */
- this.max_length = max_length; /* max bit length for the codes */
- // show if `static_tree` has data or dummy - needed for monomorphic objects
- this.has_stree = static_tree && static_tree.length;
- }
- var static_l_desc;
- var static_d_desc;
- var static_bl_desc;
- function TreeDesc(dyn_tree, stat_desc) {
- this.dyn_tree = dyn_tree; /* the dynamic tree */
- this.max_code = 0; /* largest code with non zero frequency */
- this.stat_desc = stat_desc; /* the corresponding static tree */
- }
- function d_code(dist) {
- return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
- }
- /* ===========================================================================
- * Output a short LSB first on the stream.
- * IN assertion: there is enough room in pendingBuf.
- */
- function put_short(s, w) {
- // put_byte(s, (uch)((w) & 0xff));
- // put_byte(s, (uch)((ush)(w) >> 8));
- s.pending_buf[s.pending++] = (w) & 0xff;
- s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
- }
- /* ===========================================================================
- * Send a value on a given number of bits.
- * IN assertion: length <= 16 and value fits in length bits.
- */
- function send_bits(s, value, length) {
- if (s.bi_valid > (Buf_size - length)) {
- s.bi_buf |= (value << s.bi_valid) & 0xffff;
- put_short(s, s.bi_buf);
- s.bi_buf = value >> (Buf_size - s.bi_valid);
- s.bi_valid += length - Buf_size;
- } else {
- s.bi_buf |= (value << s.bi_valid) & 0xffff;
- s.bi_valid += length;
- }
- }
- function send_code(s, c, tree) {
- send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
- }
- /* ===========================================================================
- * Reverse the first len bits of a code, using straightforward code (a faster
- * method would use a table)
- * IN assertion: 1 <= len <= 15
- */
- function bi_reverse(code, len) {
- var res = 0;
- do {
- res |= code & 1;
- code >>>= 1;
- res <<= 1;
- } while (--len > 0);
- return res >>> 1;
- }
- /* ===========================================================================
- * Flush the bit buffer, keeping at most 7 bits in it.
- */
- function bi_flush(s) {
- if (s.bi_valid === 16) {
- put_short(s, s.bi_buf);
- s.bi_buf = 0;
- s.bi_valid = 0;
- } else if (s.bi_valid >= 8) {
- s.pending_buf[s.pending++] = s.bi_buf & 0xff;
- s.bi_buf >>= 8;
- s.bi_valid -= 8;
- }
- }
- /* ===========================================================================
- * Compute the optimal bit lengths for a tree and update the total bit length
- * for the current block.
- * IN assertion: the fields freq and dad are set, heap[heap_max] and
- * above are the tree nodes sorted by increasing frequency.
- * OUT assertions: the field len is set to the optimal bit length, the
- * array bl_count contains the frequencies for each bit length.
- * The length opt_len is updated; static_len is also updated if stree is
- * not null.
- */
- function gen_bitlen(s, desc)
- // deflate_state *s;
- // tree_desc *desc; /* the tree descriptor */
- {
- var tree = desc.dyn_tree;
- var max_code = desc.max_code;
- var stree = desc.stat_desc.static_tree;
- var has_stree = desc.stat_desc.has_stree;
- var extra = desc.stat_desc.extra_bits;
- var base = desc.stat_desc.extra_base;
- var max_length = desc.stat_desc.max_length;
- var h; /* heap index */
- var n, m; /* iterate over the tree elements */
- var bits; /* bit length */
- var xbits; /* extra bits */
- var f; /* frequency */
- var overflow = 0; /* number of elements with bit length too large */
- for (bits = 0; bits <= MAX_BITS; bits++) {
- s.bl_count[bits] = 0;
- }
- /* In a first pass, compute the optimal bit lengths (which may
- * overflow in the case of the bit length tree).
- */
- tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
- for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
- n = s.heap[h];
- bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
- if (bits > max_length) {
- bits = max_length;
- overflow++;
- }
- tree[n * 2 + 1]/*.Len*/ = bits;
- /* We overwrite tree[n].Dad which is no longer needed */
- if (n > max_code) { continue; } /* not a leaf node */
- s.bl_count[bits]++;
- xbits = 0;
- if (n >= base) {
- xbits = extra[n - base];
- }
- f = tree[n * 2]/*.Freq*/;
- s.opt_len += f * (bits + xbits);
- if (has_stree) {
- s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
- }
- }
- if (overflow === 0) { return; }
- // Trace((stderr,"\nbit length overflow\n"));
- /* This happens for example on obj2 and pic of the Calgary corpus */
- /* Find the first bit length which could increase: */
- do {
- bits = max_length - 1;
- while (s.bl_count[bits] === 0) { bits--; }
- s.bl_count[bits]--; /* move one leaf down the tree */
- s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
- s.bl_count[max_length]--;
- /* The brother of the overflow item also moves one step up,
- * but this does not affect bl_count[max_length]
- */
- overflow -= 2;
- } while (overflow > 0);
- /* Now recompute all bit lengths, scanning in increasing frequency.
- * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
- * lengths instead of fixing only the wrong ones. This idea is taken
- * from 'ar' written by Haruhiko Okumura.)
- */
- for (bits = max_length; bits !== 0; bits--) {
- n = s.bl_count[bits];
- while (n !== 0) {
- m = s.heap[--h];
- if (m > max_code) { continue; }
- if (tree[m * 2 + 1]/*.Len*/ !== bits) {
- // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
- s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
- tree[m * 2 + 1]/*.Len*/ = bits;
- }
- n--;
- }
- }
- }
- /* ===========================================================================
- * Generate the codes for a given tree and bit counts (which need not be
- * optimal).
- * IN assertion: the array bl_count contains the bit length statistics for
- * the given tree and the field len is set for all tree elements.
- * OUT assertion: the field code is set for all tree elements of non
- * zero code length.
- */
- function gen_codes(tree, max_code, bl_count)
- // ct_data *tree; /* the tree to decorate */
- // int max_code; /* largest code with non zero frequency */
- // ushf *bl_count; /* number of codes at each bit length */
- {
- var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
- var code = 0; /* running code value */
- var bits; /* bit index */
- var n; /* code index */
- /* The distribution counts are first used to generate the code values
- * without bit reversal.
- */
- for (bits = 1; bits <= MAX_BITS; bits++) {
- next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
- }
- /* Check that the bit counts in bl_count are consistent. The last code
- * must be all ones.
- */
- //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
- // "inconsistent bit counts");
- //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
- for (n = 0; n <= max_code; n++) {
- var len = tree[n * 2 + 1]/*.Len*/;
- if (len === 0) { continue; }
- /* Now reverse the bits */
- tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
- //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
- // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
- }
- }
- /* ===========================================================================
- * Initialize the various 'constant' tables.
- */
- function tr_static_init() {
- var n; /* iterates over tree elements */
- var bits; /* bit counter */
- var length; /* length value */
- var code; /* code value */
- var dist; /* distance index */
- var bl_count = new Array(MAX_BITS + 1);
- /* number of codes at each bit length for an optimal tree */
- // do check in _tr_init()
- //if (static_init_done) return;
- /* For some embedded targets, global variables are not initialized: */
- /*#ifdef NO_INIT_GLOBAL_POINTERS
- static_l_desc.static_tree = static_ltree;
- static_l_desc.extra_bits = extra_lbits;
- static_d_desc.static_tree = static_dtree;
- static_d_desc.extra_bits = extra_dbits;
- static_bl_desc.extra_bits = extra_blbits;
- #endif*/
- /* Initialize the mapping length (0..255) -> length code (0..28) */
- length = 0;
- for (code = 0; code < LENGTH_CODES - 1; code++) {
- base_length[code] = length;
- for (n = 0; n < (1 << extra_lbits[code]); n++) {
- _length_code[length++] = code;
- }
- }
- //Assert (length == 256, "tr_static_init: length != 256");
- /* Note that the length 255 (match length 258) can be represented
- * in two different ways: code 284 + 5 bits or code 285, so we
- * overwrite length_code[255] to use the best encoding:
- */
- _length_code[length - 1] = code;
- /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
- dist = 0;
- for (code = 0; code < 16; code++) {
- base_dist[code] = dist;
- for (n = 0; n < (1 << extra_dbits[code]); n++) {
- _dist_code[dist++] = code;
- }
- }
- //Assert (dist == 256, "tr_static_init: dist != 256");
- dist >>= 7; /* from now on, all distances are divided by 128 */
- for (; code < D_CODES; code++) {
- base_dist[code] = dist << 7;
- for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
- _dist_code[256 + dist++] = code;
- }
- }
- //Assert (dist == 256, "tr_static_init: 256+dist != 512");
- /* Construct the codes of the static literal tree */
- for (bits = 0; bits <= MAX_BITS; bits++) {
- bl_count[bits] = 0;
- }
- n = 0;
- while (n <= 143) {
- static_ltree[n * 2 + 1]/*.Len*/ = 8;
- n++;
- bl_count[8]++;
- }
- while (n <= 255) {
- static_ltree[n * 2 + 1]/*.Len*/ = 9;
- n++;
- bl_count[9]++;
- }
- while (n <= 279) {
- static_ltree[n * 2 + 1]/*.Len*/ = 7;
- n++;
- bl_count[7]++;
- }
- while (n <= 287) {
- static_ltree[n * 2 + 1]/*.Len*/ = 8;
- n++;
- bl_count[8]++;
- }
- /* Codes 286 and 287 do not exist, but we must include them in the
- * tree construction to get a canonical Huffman tree (longest code
- * all ones)
- */
- gen_codes(static_ltree, L_CODES + 1, bl_count);
- /* The static distance tree is trivial: */
- for (n = 0; n < D_CODES; n++) {
- static_dtree[n * 2 + 1]/*.Len*/ = 5;
- static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
- }
- // Now data ready and we can init static trees
- static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
- static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
- static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
- //static_init_done = true;
- }
- /* ===========================================================================
- * Initialize a new block.
- */
- function init_block(s) {
- var n; /* iterates over tree elements */
- /* Initialize the trees. */
- for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
- for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
- for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
- s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
- s.opt_len = s.static_len = 0;
- s.last_lit = s.matches = 0;
- }
- /* ===========================================================================
- * Flush the bit buffer and align the output on a byte boundary
- */
- function bi_windup(s)
- {
- if (s.bi_valid > 8) {
- put_short(s, s.bi_buf);
- } else if (s.bi_valid > 0) {
- //put_byte(s, (Byte)s->bi_buf);
- s.pending_buf[s.pending++] = s.bi_buf;
- }
- s.bi_buf = 0;
- s.bi_valid = 0;
- }
- /* ===========================================================================
- * Copy a stored block, storing first the length and its
- * one's complement if requested.
- */
- function copy_block(s, buf, len, header)
- //DeflateState *s;
- //charf *buf; /* the input data */
- //unsigned len; /* its length */
- //int header; /* true if block header must be written */
- {
- bi_windup(s); /* align on byte boundary */
- if (header) {
- put_short(s, len);
- put_short(s, ~len);
- }
- // while (len--) {
- // put_byte(s, *buf++);
- // }
- utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
- s.pending += len;
- }
- /* ===========================================================================
- * Compares to subtrees, using the tree depth as tie breaker when
- * the subtrees have equal frequency. This minimizes the worst case length.
- */
- function smaller(tree, n, m, depth) {
- var _n2 = n * 2;
- var _m2 = m * 2;
- return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
- (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
- }
- /* ===========================================================================
- * Restore the heap property by moving down the tree starting at node k,
- * exchanging a node with the smallest of its two sons if necessary, stopping
- * when the heap property is re-established (each father smaller than its
- * two sons).
- */
- function pqdownheap(s, tree, k)
- // deflate_state *s;
- // ct_data *tree; /* the tree to restore */
- // int k; /* node to move down */
- {
- var v = s.heap[k];
- var j = k << 1; /* left son of k */
- while (j <= s.heap_len) {
- /* Set j to the smallest of the two sons: */
- if (j < s.heap_len &&
- smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
- j++;
- }
- /* Exit if v is smaller than both sons */
- if (smaller(tree, v, s.heap[j], s.depth)) { break; }
- /* Exchange v with the smallest son */
- s.heap[k] = s.heap[j];
- k = j;
- /* And continue down the tree, setting j to the left son of k */
- j <<= 1;
- }
- s.heap[k] = v;
- }
- // inlined manually
- // var SMALLEST = 1;
- /* ===========================================================================
- * Send the block data compressed using the given Huffman trees
- */
- function compress_block(s, ltree, dtree)
- // deflate_state *s;
- // const ct_data *ltree; /* literal tree */
- // const ct_data *dtree; /* distance tree */
- {
- var dist; /* distance of matched string */
- var lc; /* match length or unmatched char (if dist == 0) */
- var lx = 0; /* running index in l_buf */
- var code; /* the code to send */
- var extra; /* number of extra bits to send */
- if (s.last_lit !== 0) {
- do {
- dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
- lc = s.pending_buf[s.l_buf + lx];
- lx++;
- if (dist === 0) {
- send_code(s, lc, ltree); /* send a literal byte */
- //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
- } else {
- /* Here, lc is the match length - MIN_MATCH */
- code = _length_code[lc];
- send_code(s, code + LITERALS + 1, ltree); /* send the length code */
- extra = extra_lbits[code];
- if (extra !== 0) {
- lc -= base_length[code];
- send_bits(s, lc, extra); /* send the extra length bits */
- }
- dist--; /* dist is now the match distance - 1 */
- code = d_code(dist);
- //Assert (code < D_CODES, "bad d_code");
- send_code(s, code, dtree); /* send the distance code */
- extra = extra_dbits[code];
- if (extra !== 0) {
- dist -= base_dist[code];
- send_bits(s, dist, extra); /* send the extra distance bits */
- }
- } /* literal or match pair ? */
- /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
- //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
- // "pendingBuf overflow");
- } while (lx < s.last_lit);
- }
- send_code(s, END_BLOCK, ltree);
- }
- /* ===========================================================================
- * Construct one Huffman tree and assigns the code bit strings and lengths.
- * Update the total bit length for the current block.
- * IN assertion: the field freq is set for all tree elements.
- * OUT assertions: the fields len and code are set to the optimal bit length
- * and corresponding code. The length opt_len is updated; static_len is
- * also updated if stree is not null. The field max_code is set.
- */
- function build_tree(s, desc)
- // deflate_state *s;
- // tree_desc *desc; /* the tree descriptor */
- {
- var tree = desc.dyn_tree;
- var stree = desc.stat_desc.static_tree;
- var has_stree = desc.stat_desc.has_stree;
- var elems = desc.stat_desc.elems;
- var n, m; /* iterate over heap elements */
- var max_code = -1; /* largest code with non zero frequency */
- var node; /* new node being created */
- /* Construct the initial heap, with least frequent element in
- * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
- * heap[0] is not used.
- */
- s.heap_len = 0;
- s.heap_max = HEAP_SIZE;
- for (n = 0; n < elems; n++) {
- if (tree[n * 2]/*.Freq*/ !== 0) {
- s.heap[++s.heap_len] = max_code = n;
- s.depth[n] = 0;
- } else {
- tree[n * 2 + 1]/*.Len*/ = 0;
- }
- }
- /* The pkzip format requires that at least one distance code exists,
- * and that at least one bit should be sent even if there is only one
- * possible code. So to avoid special checks later on we force at least
- * two codes of non zero frequency.
- */
- while (s.heap_len < 2) {
- node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
- tree[node * 2]/*.Freq*/ = 1;
- s.depth[node] = 0;
- s.opt_len--;
- if (has_stree) {
- s.static_len -= stree[node * 2 + 1]/*.Len*/;
- }
- /* node is 0 or 1 so it does not have extra bits */
- }
- desc.max_code = max_code;
- /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
- * establish sub-heaps of increasing lengths:
- */
- for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
- /* Construct the Huffman tree by repeatedly combining the least two
- * frequent nodes.
- */
- node = elems; /* next internal node of the tree */
- do {
- //pqremove(s, tree, n); /* n = node of least frequency */
- /*** pqremove ***/
- n = s.heap[1/*SMALLEST*/];
- s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
- pqdownheap(s, tree, 1/*SMALLEST*/);
- /***/
- m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
- s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
- s.heap[--s.heap_max] = m;
- /* Create a new node father of n and m */
- tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
- s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
- tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
- /* and insert the new node in the heap */
- s.heap[1/*SMALLEST*/] = node++;
- pqdownheap(s, tree, 1/*SMALLEST*/);
- } while (s.heap_len >= 2);
- s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
- /* At this point, the fields freq and dad are set. We can now
- * generate the bit lengths.
- */
- gen_bitlen(s, desc);
- /* The field len is now set, we can generate the bit codes */
- gen_codes(tree, max_code, s.bl_count);
- }
- /* ===========================================================================
- * Scan a literal or distance tree to determine the frequencies of the codes
- * in the bit length tree.
- */
- function scan_tree(s, tree, max_code)
- // deflate_state *s;
- // ct_data *tree; /* the tree to be scanned */
- // int max_code; /* and its largest code of non zero frequency */
- {
- var n; /* iterates over all tree elements */
- var prevlen = -1; /* last emitted length */
- var curlen; /* length of current code */
- var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
- var count = 0; /* repeat count of the current code */
- var max_count = 7; /* max repeat count */
- var min_count = 4; /* min repeat count */
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- }
- tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
- for (n = 0; n <= max_code; n++) {
- curlen = nextlen;
- nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
- if (++count < max_count && curlen === nextlen) {
- continue;
- } else if (count < min_count) {
- s.bl_tree[curlen * 2]/*.Freq*/ += count;
- } else if (curlen !== 0) {
- if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
- s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
- } else if (count <= 10) {
- s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
- } else {
- s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
- }
- count = 0;
- prevlen = curlen;
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- } else if (curlen === nextlen) {
- max_count = 6;
- min_count = 3;
- } else {
- max_count = 7;
- min_count = 4;
- }
- }
- }
- /* ===========================================================================
- * Send a literal or distance tree in compressed form, using the codes in
- * bl_tree.
- */
- function send_tree(s, tree, max_code)
- // deflate_state *s;
- // ct_data *tree; /* the tree to be scanned */
- // int max_code; /* and its largest code of non zero frequency */
- {
- var n; /* iterates over all tree elements */
- var prevlen = -1; /* last emitted length */
- var curlen; /* length of current code */
- var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
- var count = 0; /* repeat count of the current code */
- var max_count = 7; /* max repeat count */
- var min_count = 4; /* min repeat count */
- /* tree[max_code+1].Len = -1; */ /* guard already set */
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- }
- for (n = 0; n <= max_code; n++) {
- curlen = nextlen;
- nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
- if (++count < max_count && curlen === nextlen) {
- continue;
- } else if (count < min_count) {
- do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
- } else if (curlen !== 0) {
- if (curlen !== prevlen) {
- send_code(s, curlen, s.bl_tree);
- count--;
- }
- //Assert(count >= 3 && count <= 6, " 3_6?");
- send_code(s, REP_3_6, s.bl_tree);
- send_bits(s, count - 3, 2);
- } else if (count <= 10) {
- send_code(s, REPZ_3_10, s.bl_tree);
- send_bits(s, count - 3, 3);
- } else {
- send_code(s, REPZ_11_138, s.bl_tree);
- send_bits(s, count - 11, 7);
- }
- count = 0;
- prevlen = curlen;
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- } else if (curlen === nextlen) {
- max_count = 6;
- min_count = 3;
- } else {
- max_count = 7;
- min_count = 4;
- }
- }
- }
- /* ===========================================================================
- * Construct the Huffman tree for the bit lengths and return the index in
- * bl_order of the last bit length code to send.
- */
- function build_bl_tree(s) {
- var max_blindex; /* index of last bit length code of non zero freq */
- /* Determine the bit length frequencies for literal and distance trees */
- scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
- scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
- /* Build the bit length tree: */
- build_tree(s, s.bl_desc);
- /* opt_len now includes the length of the tree representations, except
- * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
- */
- /* Determine the number of bit length codes to send. The pkzip format
- * requires that at least 4 bit length codes be sent. (appnote.txt says
- * 3 but the actual value used is 4.)
- */
- for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
- if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
- break;
- }
- }
- /* Update opt_len to include the bit length tree and counts */
- s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
- //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
- // s->opt_len, s->static_len));
- return max_blindex;
- }
- /* ===========================================================================
- * Send the header for a block using dynamic Huffman trees: the counts, the
- * lengths of the bit length codes, the literal tree and the distance tree.
- * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
- */
- function send_all_trees(s, lcodes, dcodes, blcodes)
- // deflate_state *s;
- // int lcodes, dcodes, blcodes; /* number of codes for each tree */
- {
- var rank; /* index in bl_order */
- //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
- //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
- // "too many codes");
- //Tracev((stderr, "\nbl counts: "));
- send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
- send_bits(s, dcodes - 1, 5);
- send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
- for (rank = 0; rank < blcodes; rank++) {
- //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
- send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
- }
- //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
- send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
- //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
- send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
- //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
- }
- /* ===========================================================================
- * Check if the data type is TEXT or BINARY, using the following algorithm:
- * - TEXT if the two conditions below are satisfied:
- * a) There are no non-portable control characters belonging to the
- * "black list" (0..6, 14..25, 28..31).
- * b) There is at least one printable character belonging to the
- * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
- * - BINARY otherwise.
- * - The following partially-portable control characters form a
- * "gray list" that is ignored in this detection algorithm:
- * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
- * IN assertion: the fields Freq of dyn_ltree are set.
- */
- function detect_data_type(s) {
- /* black_mask is the bit mask of black-listed bytes
- * set bits 0..6, 14..25, and 28..31
- * 0xf3ffc07f = binary 11110011111111111100000001111111
- */
- var black_mask = 0xf3ffc07f;
- var n;
- /* Check for non-textual ("black-listed") bytes. */
- for (n = 0; n <= 31; n++, black_mask >>>= 1) {
- if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
- return Z_BINARY;
- }
- }
- /* Check for textual ("white-listed") bytes. */
- if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
- s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
- return Z_TEXT;
- }
- for (n = 32; n < LITERALS; n++) {
- if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
- return Z_TEXT;
- }
- }
- /* There are no "black-listed" or "white-listed" bytes:
- * this stream either is empty or has tolerated ("gray-listed") bytes only.
- */
- return Z_BINARY;
- }
- var static_init_done = false;
- /* ===========================================================================
- * Initialize the tree data structures for a new zlib stream.
- */
- function _tr_init(s)
- {
- if (!static_init_done) {
- tr_static_init();
- static_init_done = true;
- }
- s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
- s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
- s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
- s.bi_buf = 0;
- s.bi_valid = 0;
- /* Initialize the first block of the first file: */
- init_block(s);
- }
- /* ===========================================================================
- * Send a stored block
- */
- function _tr_stored_block(s, buf, stored_len, last)
- //DeflateState *s;
- //charf *buf; /* input block */
- //ulg stored_len; /* length of input block */
- //int last; /* one if this is the last block for a file */
- {
- send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
- copy_block(s, buf, stored_len, true); /* with header */
- }
- /* ===========================================================================
- * Send one empty static block to give enough lookahead for inflate.
- * This takes 10 bits, of which 7 may remain in the bit buffer.
- */
- function _tr_align(s) {
- send_bits(s, STATIC_TREES << 1, 3);
- send_code(s, END_BLOCK, static_ltree);
- bi_flush(s);
- }
- /* ===========================================================================
- * Determine the best encoding for the current block: dynamic trees, static
- * trees or store, and output the encoded block to the zip file.
- */
- function _tr_flush_block(s, buf, stored_len, last)
- //DeflateState *s;
- //charf *buf; /* input block, or NULL if too old */
- //ulg stored_len; /* length of input block */
- //int last; /* one if this is the last block for a file */
- {
- var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
- var max_blindex = 0; /* index of last bit length code of non zero freq */
- /* Build the Huffman trees unless a stored block is forced */
- if (s.level > 0) {
- /* Check if the file is binary or text */
- if (s.strm.data_type === Z_UNKNOWN) {
- s.strm.data_type = detect_data_type(s);
- }
- /* Construct the literal and distance trees */
- build_tree(s, s.l_desc);
- // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
- // s->static_len));
- build_tree(s, s.d_desc);
- // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
- // s->static_len));
- /* At this point, opt_len and static_len are the total bit lengths of
- * the compressed block data, excluding the tree representations.
- */
- /* Build the bit length tree for the above two trees, and get the index
- * in bl_order of the last bit length code to send.
- */
- max_blindex = build_bl_tree(s);
- /* Determine the best encoding. Compute the block lengths in bytes. */
- opt_lenb = (s.opt_len + 3 + 7) >>> 3;
- static_lenb = (s.static_len + 3 + 7) >>> 3;
- // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
- // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
- // s->last_lit));
- if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
- } else {
- // Assert(buf != (char*)0, "lost buf");
- opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
- }
- if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
- /* 4: two words for the lengths */
- /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
- * Otherwise we can't have processed more than WSIZE input bytes since
- * the last block flush, because compression would have been
- * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
- * transform a block into a stored block.
- */
- _tr_stored_block(s, buf, stored_len, last);
- } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
- send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
- compress_block(s, static_ltree, static_dtree);
- } else {
- send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
- send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
- compress_block(s, s.dyn_ltree, s.dyn_dtree);
- }
- // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
- /* The above check is made mod 2^32, for files larger than 512 MB
- * and uLong implemented on 32 bits.
- */
- init_block(s);
- if (last) {
- bi_windup(s);
- }
- // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
- // s->compressed_len-7*last));
- }
- /* ===========================================================================
- * Save the match info and tally the frequency counts. Return true if
- * the current block must be flushed.
- */
- function _tr_tally(s, dist, lc)
- // deflate_state *s;
- // unsigned dist; /* distance of matched string */
- // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
- {
- //var out_length, in_length, dcode;
- s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
- s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
- s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
- s.last_lit++;
- if (dist === 0) {
- /* lc is the unmatched char */
- s.dyn_ltree[lc * 2]/*.Freq*/++;
- } else {
- s.matches++;
- /* Here, lc is the match length - MIN_MATCH */
- dist--; /* dist = match distance - 1 */
- //Assert((ush)dist < (ush)MAX_DIST(s) &&
- // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
- // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
- s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
- s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
- }
- // (!) This block is disabled in zlib defaults,
- // don't enable it for binary compatibility
- //#ifdef TRUNCATE_BLOCK
- // /* Try to guess if it is profitable to stop the current block here */
- // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
- // /* Compute an upper bound for the compressed length */
- // out_length = s.last_lit*8;
- // in_length = s.strstart - s.block_start;
- //
- // for (dcode = 0; dcode < D_CODES; dcode++) {
- // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
- // }
- // out_length >>>= 3;
- // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
- // // s->last_lit, in_length, out_length,
- // // 100L - out_length*100L/in_length));
- // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
- // return true;
- // }
- // }
- //#endif
- return (s.last_lit === s.lit_bufsize - 1);
- /* We avoid equality with lit_bufsize because of wraparound at 64K
- * on 16 bit machines and because stored blocks are restricted to
- * 64K-1 bytes.
- */
- }
- exports._tr_init = _tr_init;
- exports._tr_stored_block = _tr_stored_block;
- exports._tr_flush_block = _tr_flush_block;
- exports._tr_tally = _tr_tally;
- exports._tr_align = _tr_align;
- },{"../utils/common":35}],45:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- function ZStream() {
- /* next input byte */
- this.input = null; // JS specific, because we have no pointers
- this.next_in = 0;
- /* number of bytes available at input */
- this.avail_in = 0;
- /* total number of input bytes read so far */
- this.total_in = 0;
- /* next output byte should be put there */
- this.output = null; // JS specific, because we have no pointers
- this.next_out = 0;
- /* remaining free space at output */
- this.avail_out = 0;
- /* total number of bytes output so far */
- this.total_out = 0;
- /* last error message, NULL if no error */
- this.msg = ''/*Z_NULL*/;
- /* not visible by applications */
- this.state = null;
- /* best guess about the data type: binary or text */
- this.data_type = 2/*Z_UNKNOWN*/;
- /* adler32 value of the uncompressed data */
- this.adler = 0;
- }
- module.exports = ZStream;
- },{}],46:[function(require,module,exports){
- arguments[4][32][0].apply(exports,arguments)
- },{"dup":32}],47:[function(require,module,exports){
- (function (Buffer){
- /*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh <https://feross.org>
- * @license MIT
- */
- /* eslint-disable no-proto */
- 'use strict'
- var base64 = require('base64-js')
- var ieee754 = require('ieee754')
- var customInspectSymbol =
- (typeof Symbol === 'function' && typeof Symbol.for === 'function')
- ? Symbol.for('nodejs.util.inspect.custom')
- : null
- exports.Buffer = Buffer
- exports.SlowBuffer = SlowBuffer
- exports.INSPECT_MAX_BYTES = 50
- var K_MAX_LENGTH = 0x7fffffff
- exports.kMaxLength = K_MAX_LENGTH
- /**
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
- * === true Use Uint8Array implementation (fastest)
- * === false Print warning and recommend using `buffer` v4.x which has an Object
- * implementation (most compatible, even IE6)
- *
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
- * Opera 11.6+, iOS 4.2+.
- *
- * We report that the browser does not support typed arrays if the are not subclassable
- * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
- * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
- * for __proto__ and has a buggy typed array implementation.
- */
- Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
- if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
- typeof console.error === 'function') {
- console.error(
- 'This browser lacks typed array (Uint8Array) support which is required by ' +
- '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
- )
- }
- function typedArraySupport () {
- // Can typed array instances can be augmented?
- try {
- var arr = new Uint8Array(1)
- var proto = { foo: function () { return 42 } }
- Object.setPrototypeOf(proto, Uint8Array.prototype)
- Object.setPrototypeOf(arr, proto)
- return arr.foo() === 42
- } catch (e) {
- return false
- }
- }
- Object.defineProperty(Buffer.prototype, 'parent', {
- enumerable: true,
- get: function () {
- if (!Buffer.isBuffer(this)) return undefined
- return this.buffer
- }
- })
- Object.defineProperty(Buffer.prototype, 'offset', {
- enumerable: true,
- get: function () {
- if (!Buffer.isBuffer(this)) return undefined
- return this.byteOffset
- }
- })
- function createBuffer (length) {
- if (length > K_MAX_LENGTH) {
- throw new RangeError('The value "' + length + '" is invalid for option "size"')
- }
- // Return an augmented `Uint8Array` instance
- var buf = new Uint8Array(length)
- Object.setPrototypeOf(buf, Buffer.prototype)
- return buf
- }
- /**
- * The Buffer constructor returns instances of `Uint8Array` that have their
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
- * returns a single octet.
- *
- * The `Uint8Array` prototype remains unmodified.
- */
- function Buffer (arg, encodingOrOffset, length) {
- // Common case.
- if (typeof arg === 'number') {
- if (typeof encodingOrOffset === 'string') {
- throw new TypeError(
- 'The "string" argument must be of type string. Received type number'
- )
- }
- return allocUnsafe(arg)
- }
- return from(arg, encodingOrOffset, length)
- }
- // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
- if (typeof Symbol !== 'undefined' && Symbol.species != null &&
- Buffer[Symbol.species] === Buffer) {
- Object.defineProperty(Buffer, Symbol.species, {
- value: null,
- configurable: true,
- enumerable: false,
- writable: false
- })
- }
- Buffer.poolSize = 8192 // not used by this implementation
- function from (value, encodingOrOffset, length) {
- if (typeof value === 'string') {
- return fromString(value, encodingOrOffset)
- }
- if (ArrayBuffer.isView(value)) {
- return fromArrayLike(value)
- }
- if (value == null) {
- throw new TypeError(
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
- 'or Array-like Object. Received type ' + (typeof value)
- )
- }
- if (isInstance(value, ArrayBuffer) ||
- (value && isInstance(value.buffer, ArrayBuffer))) {
- return fromArrayBuffer(value, encodingOrOffset, length)
- }
- if (typeof value === 'number') {
- throw new TypeError(
- 'The "value" argument must not be of type number. Received type number'
- )
- }
- var valueOf = value.valueOf && value.valueOf()
- if (valueOf != null && valueOf !== value) {
- return Buffer.from(valueOf, encodingOrOffset, length)
- }
- var b = fromObject(value)
- if (b) return b
- if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
- typeof value[Symbol.toPrimitive] === 'function') {
- return Buffer.from(
- value[Symbol.toPrimitive]('string'), encodingOrOffset, length
- )
- }
- throw new TypeError(
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
- 'or Array-like Object. Received type ' + (typeof value)
- )
- }
- /**
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
- * if value is a number.
- * Buffer.from(str[, encoding])
- * Buffer.from(array)
- * Buffer.from(buffer)
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
- **/
- Buffer.from = function (value, encodingOrOffset, length) {
- return from(value, encodingOrOffset, length)
- }
- // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
- // https://github.com/feross/buffer/pull/148
- Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
- Object.setPrototypeOf(Buffer, Uint8Array)
- function assertSize (size) {
- if (typeof size !== 'number') {
- throw new TypeError('"size" argument must be of type number')
- } else if (size < 0) {
- throw new RangeError('The value "' + size + '" is invalid for option "size"')
- }
- }
- function alloc (size, fill, encoding) {
- assertSize(size)
- if (size <= 0) {
- return createBuffer(size)
- }
- if (fill !== undefined) {
- // Only pay attention to encoding if it's a string. This
- // prevents accidentally sending in a number that would
- // be interpretted as a start offset.
- return typeof encoding === 'string'
- ? createBuffer(size).fill(fill, encoding)
- : createBuffer(size).fill(fill)
- }
- return createBuffer(size)
- }
- /**
- * Creates a new filled Buffer instance.
- * alloc(size[, fill[, encoding]])
- **/
- Buffer.alloc = function (size, fill, encoding) {
- return alloc(size, fill, encoding)
- }
- function allocUnsafe (size) {
- assertSize(size)
- return createBuffer(size < 0 ? 0 : checked(size) | 0)
- }
- /**
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
- * */
- Buffer.allocUnsafe = function (size) {
- return allocUnsafe(size)
- }
- /**
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
- */
- Buffer.allocUnsafeSlow = function (size) {
- return allocUnsafe(size)
- }
- function fromString (string, encoding) {
- if (typeof encoding !== 'string' || encoding === '') {
- encoding = 'utf8'
- }
- if (!Buffer.isEncoding(encoding)) {
- throw new TypeError('Unknown encoding: ' + encoding)
- }
- var length = byteLength(string, encoding) | 0
- var buf = createBuffer(length)
- var actual = buf.write(string, encoding)
- if (actual !== length) {
- // Writing a hex string, for example, that contains invalid characters will
- // cause everything after the first invalid character to be ignored. (e.g.
- // 'abxxcd' will be treated as 'ab')
- buf = buf.slice(0, actual)
- }
- return buf
- }
- function fromArrayLike (array) {
- var length = array.length < 0 ? 0 : checked(array.length) | 0
- var buf = createBuffer(length)
- for (var i = 0; i < length; i += 1) {
- buf[i] = array[i] & 255
- }
- return buf
- }
- function fromArrayBuffer (array, byteOffset, length) {
- if (byteOffset < 0 || array.byteLength < byteOffset) {
- throw new RangeError('"offset" is outside of buffer bounds')
- }
- if (array.byteLength < byteOffset + (length || 0)) {
- throw new RangeError('"length" is outside of buffer bounds')
- }
- var buf
- if (byteOffset === undefined && length === undefined) {
- buf = new Uint8Array(array)
- } else if (length === undefined) {
- buf = new Uint8Array(array, byteOffset)
- } else {
- buf = new Uint8Array(array, byteOffset, length)
- }
- // Return an augmented `Uint8Array` instance
- Object.setPrototypeOf(buf, Buffer.prototype)
- return buf
- }
- function fromObject (obj) {
- if (Buffer.isBuffer(obj)) {
- var len = checked(obj.length) | 0
- var buf = createBuffer(len)
- if (buf.length === 0) {
- return buf
- }
- obj.copy(buf, 0, 0, len)
- return buf
- }
- if (obj.length !== undefined) {
- if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
- return createBuffer(0)
- }
- return fromArrayLike(obj)
- }
- if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
- return fromArrayLike(obj.data)
- }
- }
- function checked (length) {
- // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
- // length is NaN (which is otherwise coerced to zero.)
- if (length >= K_MAX_LENGTH) {
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
- 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
- }
- return length | 0
- }
- function SlowBuffer (length) {
- if (+length != length) { // eslint-disable-line eqeqeq
- length = 0
- }
- return Buffer.alloc(+length)
- }
- Buffer.isBuffer = function isBuffer (b) {
- return b != null && b._isBuffer === true &&
- b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
- }
- Buffer.compare = function compare (a, b) {
- if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
- if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
- throw new TypeError(
- 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
- )
- }
- if (a === b) return 0
- var x = a.length
- var y = b.length
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i]
- y = b[i]
- break
- }
- }
- if (x < y) return -1
- if (y < x) return 1
- return 0
- }
- Buffer.isEncoding = function isEncoding (encoding) {
- switch (String(encoding).toLowerCase()) {
- case 'hex':
- case 'utf8':
- case 'utf-8':
- case 'ascii':
- case 'latin1':
- case 'binary':
- case 'base64':
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return true
- default:
- return false
- }
- }
- Buffer.concat = function concat (list, length) {
- if (!Array.isArray(list)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
- if (list.length === 0) {
- return Buffer.alloc(0)
- }
- var i
- if (length === undefined) {
- length = 0
- for (i = 0; i < list.length; ++i) {
- length += list[i].length
- }
- }
- var buffer = Buffer.allocUnsafe(length)
- var pos = 0
- for (i = 0; i < list.length; ++i) {
- var buf = list[i]
- if (isInstance(buf, Uint8Array)) {
- buf = Buffer.from(buf)
- }
- if (!Buffer.isBuffer(buf)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
- buf.copy(buffer, pos)
- pos += buf.length
- }
- return buffer
- }
- function byteLength (string, encoding) {
- if (Buffer.isBuffer(string)) {
- return string.length
- }
- if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
- return string.byteLength
- }
- if (typeof string !== 'string') {
- throw new TypeError(
- 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
- 'Received type ' + typeof string
- )
- }
- var len = string.length
- var mustMatch = (arguments.length > 2 && arguments[2] === true)
- if (!mustMatch && len === 0) return 0
- // Use a for loop to avoid recursion
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'ascii':
- case 'latin1':
- case 'binary':
- return len
- case 'utf8':
- case 'utf-8':
- return utf8ToBytes(string).length
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return len * 2
- case 'hex':
- return len >>> 1
- case 'base64':
- return base64ToBytes(string).length
- default:
- if (loweredCase) {
- return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
- }
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
- }
- Buffer.byteLength = byteLength
- function slowToString (encoding, start, end) {
- var loweredCase = false
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
- // property of a typed array.
- // This behaves neither like String nor Uint8Array in that we set start/end
- // to their upper/lower bounds if the value passed is out of range.
- // undefined is handled specially as per ECMA-262 6th Edition,
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
- if (start === undefined || start < 0) {
- start = 0
- }
- // Return early if start > this.length. Done here to prevent potential uint32
- // coercion fail below.
- if (start > this.length) {
- return ''
- }
- if (end === undefined || end > this.length) {
- end = this.length
- }
- if (end <= 0) {
- return ''
- }
- // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
- end >>>= 0
- start >>>= 0
- if (end <= start) {
- return ''
- }
- if (!encoding) encoding = 'utf8'
- while (true) {
- switch (encoding) {
- case 'hex':
- return hexSlice(this, start, end)
- case 'utf8':
- case 'utf-8':
- return utf8Slice(this, start, end)
- case 'ascii':
- return asciiSlice(this, start, end)
- case 'latin1':
- case 'binary':
- return latin1Slice(this, start, end)
- case 'base64':
- return base64Slice(this, start, end)
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return utf16leSlice(this, start, end)
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = (encoding + '').toLowerCase()
- loweredCase = true
- }
- }
- }
- // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
- // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
- // reliably in a browserify context because there could be multiple different
- // copies of the 'buffer' package in use. This method works even for Buffer
- // instances that were created from another copy of the `buffer` package.
- // See: https://github.com/feross/buffer/issues/154
- Buffer.prototype._isBuffer = true
- function swap (b, n, m) {
- var i = b[n]
- b[n] = b[m]
- b[m] = i
- }
- Buffer.prototype.swap16 = function swap16 () {
- var len = this.length
- if (len % 2 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 16-bits')
- }
- for (var i = 0; i < len; i += 2) {
- swap(this, i, i + 1)
- }
- return this
- }
- Buffer.prototype.swap32 = function swap32 () {
- var len = this.length
- if (len % 4 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 32-bits')
- }
- for (var i = 0; i < len; i += 4) {
- swap(this, i, i + 3)
- swap(this, i + 1, i + 2)
- }
- return this
- }
- Buffer.prototype.swap64 = function swap64 () {
- var len = this.length
- if (len % 8 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 64-bits')
- }
- for (var i = 0; i < len; i += 8) {
- swap(this, i, i + 7)
- swap(this, i + 1, i + 6)
- swap(this, i + 2, i + 5)
- swap(this, i + 3, i + 4)
- }
- return this
- }
- Buffer.prototype.toString = function toString () {
- var length = this.length
- if (length === 0) return ''
- if (arguments.length === 0) return utf8Slice(this, 0, length)
- return slowToString.apply(this, arguments)
- }
- Buffer.prototype.toLocaleString = Buffer.prototype.toString
- Buffer.prototype.equals = function equals (b) {
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
- if (this === b) return true
- return Buffer.compare(this, b) === 0
- }
- Buffer.prototype.inspect = function inspect () {
- var str = ''
- var max = exports.INSPECT_MAX_BYTES
- str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
- if (this.length > max) str += ' ... '
- return '<Buffer ' + str + '>'
- }
- if (customInspectSymbol) {
- Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
- }
- Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
- if (isInstance(target, Uint8Array)) {
- target = Buffer.from(target, target.offset, target.byteLength)
- }
- if (!Buffer.isBuffer(target)) {
- throw new TypeError(
- 'The "target" argument must be one of type Buffer or Uint8Array. ' +
- 'Received type ' + (typeof target)
- )
- }
- if (start === undefined) {
- start = 0
- }
- if (end === undefined) {
- end = target ? target.length : 0
- }
- if (thisStart === undefined) {
- thisStart = 0
- }
- if (thisEnd === undefined) {
- thisEnd = this.length
- }
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
- throw new RangeError('out of range index')
- }
- if (thisStart >= thisEnd && start >= end) {
- return 0
- }
- if (thisStart >= thisEnd) {
- return -1
- }
- if (start >= end) {
- return 1
- }
- start >>>= 0
- end >>>= 0
- thisStart >>>= 0
- thisEnd >>>= 0
- if (this === target) return 0
- var x = thisEnd - thisStart
- var y = end - start
- var len = Math.min(x, y)
- var thisCopy = this.slice(thisStart, thisEnd)
- var targetCopy = target.slice(start, end)
- for (var i = 0; i < len; ++i) {
- if (thisCopy[i] !== targetCopy[i]) {
- x = thisCopy[i]
- y = targetCopy[i]
- break
- }
- }
- if (x < y) return -1
- if (y < x) return 1
- return 0
- }
- // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
- // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
- //
- // Arguments:
- // - buffer - a Buffer to search
- // - val - a string, Buffer, or number
- // - byteOffset - an index into `buffer`; will be clamped to an int32
- // - encoding - an optional encoding, relevant is val is a string
- // - dir - true for indexOf, false for lastIndexOf
- function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
- // Empty buffer means no match
- if (buffer.length === 0) return -1
- // Normalize byteOffset
- if (typeof byteOffset === 'string') {
- encoding = byteOffset
- byteOffset = 0
- } else if (byteOffset > 0x7fffffff) {
- byteOffset = 0x7fffffff
- } else if (byteOffset < -0x80000000) {
- byteOffset = -0x80000000
- }
- byteOffset = +byteOffset // Coerce to Number.
- if (numberIsNaN(byteOffset)) {
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
- byteOffset = dir ? 0 : (buffer.length - 1)
- }
- // Normalize byteOffset: negative offsets start from the end of the buffer
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset
- if (byteOffset >= buffer.length) {
- if (dir) return -1
- else byteOffset = buffer.length - 1
- } else if (byteOffset < 0) {
- if (dir) byteOffset = 0
- else return -1
- }
- // Normalize val
- if (typeof val === 'string') {
- val = Buffer.from(val, encoding)
- }
- // Finally, search either indexOf (if dir is true) or lastIndexOf
- if (Buffer.isBuffer(val)) {
- // Special case: looking for empty string/buffer always fails
- if (val.length === 0) {
- return -1
- }
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
- } else if (typeof val === 'number') {
- val = val & 0xFF // Search for a byte value [0-255]
- if (typeof Uint8Array.prototype.indexOf === 'function') {
- if (dir) {
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
- } else {
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
- }
- }
- return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
- }
- throw new TypeError('val must be string, number or Buffer')
- }
- function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
- var indexSize = 1
- var arrLength = arr.length
- var valLength = val.length
- if (encoding !== undefined) {
- encoding = String(encoding).toLowerCase()
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
- encoding === 'utf16le' || encoding === 'utf-16le') {
- if (arr.length < 2 || val.length < 2) {
- return -1
- }
- indexSize = 2
- arrLength /= 2
- valLength /= 2
- byteOffset /= 2
- }
- }
- function read (buf, i) {
- if (indexSize === 1) {
- return buf[i]
- } else {
- return buf.readUInt16BE(i * indexSize)
- }
- }
- var i
- if (dir) {
- var foundIndex = -1
- for (i = byteOffset; i < arrLength; i++) {
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
- if (foundIndex === -1) foundIndex = i
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
- } else {
- if (foundIndex !== -1) i -= i - foundIndex
- foundIndex = -1
- }
- }
- } else {
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
- for (i = byteOffset; i >= 0; i--) {
- var found = true
- for (var j = 0; j < valLength; j++) {
- if (read(arr, i + j) !== read(val, j)) {
- found = false
- break
- }
- }
- if (found) return i
- }
- }
- return -1
- }
- Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
- return this.indexOf(val, byteOffset, encoding) !== -1
- }
- Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
- }
- Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
- }
- function hexWrite (buf, string, offset, length) {
- offset = Number(offset) || 0
- var remaining = buf.length - offset
- if (!length) {
- length = remaining
- } else {
- length = Number(length)
- if (length > remaining) {
- length = remaining
- }
- }
- var strLen = string.length
- if (length > strLen / 2) {
- length = strLen / 2
- }
- for (var i = 0; i < length; ++i) {
- var parsed = parseInt(string.substr(i * 2, 2), 16)
- if (numberIsNaN(parsed)) return i
- buf[offset + i] = parsed
- }
- return i
- }
- function utf8Write (buf, string, offset, length) {
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
- }
- function asciiWrite (buf, string, offset, length) {
- return blitBuffer(asciiToBytes(string), buf, offset, length)
- }
- function latin1Write (buf, string, offset, length) {
- return asciiWrite(buf, string, offset, length)
- }
- function base64Write (buf, string, offset, length) {
- return blitBuffer(base64ToBytes(string), buf, offset, length)
- }
- function ucs2Write (buf, string, offset, length) {
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
- }
- Buffer.prototype.write = function write (string, offset, length, encoding) {
- // Buffer#write(string)
- if (offset === undefined) {
- encoding = 'utf8'
- length = this.length
- offset = 0
- // Buffer#write(string, encoding)
- } else if (length === undefined && typeof offset === 'string') {
- encoding = offset
- length = this.length
- offset = 0
- // Buffer#write(string, offset[, length][, encoding])
- } else if (isFinite(offset)) {
- offset = offset >>> 0
- if (isFinite(length)) {
- length = length >>> 0
- if (encoding === undefined) encoding = 'utf8'
- } else {
- encoding = length
- length = undefined
- }
- } else {
- throw new Error(
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
- )
- }
- var remaining = this.length - offset
- if (length === undefined || length > remaining) length = remaining
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
- throw new RangeError('Attempt to write outside buffer bounds')
- }
- if (!encoding) encoding = 'utf8'
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'hex':
- return hexWrite(this, string, offset, length)
- case 'utf8':
- case 'utf-8':
- return utf8Write(this, string, offset, length)
- case 'ascii':
- return asciiWrite(this, string, offset, length)
- case 'latin1':
- case 'binary':
- return latin1Write(this, string, offset, length)
- case 'base64':
- // Warning: maxLength not taken into account in base64Write
- return base64Write(this, string, offset, length)
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return ucs2Write(this, string, offset, length)
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
- }
- Buffer.prototype.toJSON = function toJSON () {
- return {
- type: 'Buffer',
- data: Array.prototype.slice.call(this._arr || this, 0)
- }
- }
- function base64Slice (buf, start, end) {
- if (start === 0 && end === buf.length) {
- return base64.fromByteArray(buf)
- } else {
- return base64.fromByteArray(buf.slice(start, end))
- }
- }
- function utf8Slice (buf, start, end) {
- end = Math.min(buf.length, end)
- var res = []
- var i = start
- while (i < end) {
- var firstByte = buf[i]
- var codePoint = null
- var bytesPerSequence = (firstByte > 0xEF) ? 4
- : (firstByte > 0xDF) ? 3
- : (firstByte > 0xBF) ? 2
- : 1
- if (i + bytesPerSequence <= end) {
- var secondByte, thirdByte, fourthByte, tempCodePoint
- switch (bytesPerSequence) {
- case 1:
- if (firstByte < 0x80) {
- codePoint = firstByte
- }
- break
- case 2:
- secondByte = buf[i + 1]
- if ((secondByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
- if (tempCodePoint > 0x7F) {
- codePoint = tempCodePoint
- }
- }
- break
- case 3:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
- codePoint = tempCodePoint
- }
- }
- break
- case 4:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- fourthByte = buf[i + 3]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
- codePoint = tempCodePoint
- }
- }
- }
- }
- if (codePoint === null) {
- // we did not generate a valid codePoint so insert a
- // replacement char (U+FFFD) and advance only 1 byte
- codePoint = 0xFFFD
- bytesPerSequence = 1
- } else if (codePoint > 0xFFFF) {
- // encode to utf16 (surrogate pair dance)
- codePoint -= 0x10000
- res.push(codePoint >>> 10 & 0x3FF | 0xD800)
- codePoint = 0xDC00 | codePoint & 0x3FF
- }
- res.push(codePoint)
- i += bytesPerSequence
- }
- return decodeCodePointsArray(res)
- }
- // Based on http://stackoverflow.com/a/22747272/680742, the browser with
- // the lowest limit is Chrome, with 0x10000 args.
- // We go 1 magnitude less, for safety
- var MAX_ARGUMENTS_LENGTH = 0x1000
- function decodeCodePointsArray (codePoints) {
- var len = codePoints.length
- if (len <= MAX_ARGUMENTS_LENGTH) {
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
- }
- // Decode in chunks to avoid "call stack size exceeded".
- var res = ''
- var i = 0
- while (i < len) {
- res += String.fromCharCode.apply(
- String,
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
- )
- }
- return res
- }
- function asciiSlice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i] & 0x7F)
- }
- return ret
- }
- function latin1Slice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i])
- }
- return ret
- }
- function hexSlice (buf, start, end) {
- var len = buf.length
- if (!start || start < 0) start = 0
- if (!end || end < 0 || end > len) end = len
- var out = ''
- for (var i = start; i < end; ++i) {
- out += hexSliceLookupTable[buf[i]]
- }
- return out
- }
- function utf16leSlice (buf, start, end) {
- var bytes = buf.slice(start, end)
- var res = ''
- for (var i = 0; i < bytes.length; i += 2) {
- res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
- }
- return res
- }
- Buffer.prototype.slice = function slice (start, end) {
- var len = this.length
- start = ~~start
- end = end === undefined ? len : ~~end
- if (start < 0) {
- start += len
- if (start < 0) start = 0
- } else if (start > len) {
- start = len
- }
- if (end < 0) {
- end += len
- if (end < 0) end = 0
- } else if (end > len) {
- end = len
- }
- if (end < start) end = start
- var newBuf = this.subarray(start, end)
- // Return an augmented `Uint8Array` instance
- Object.setPrototypeOf(newBuf, Buffer.prototype)
- return newBuf
- }
- /*
- * Need to make sure that buffer isn't trying to write out of bounds.
- */
- function checkOffset (offset, ext, length) {
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
- }
- Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
- return val
- }
- Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) {
- checkOffset(offset, byteLength, this.length)
- }
- var val = this[offset + --byteLength]
- var mul = 1
- while (byteLength > 0 && (mul *= 0x100)) {
- val += this[offset + --byteLength] * mul
- }
- return val
- }
- Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 1, this.length)
- return this[offset]
- }
- Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- return this[offset] | (this[offset + 1] << 8)
- }
- Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- return (this[offset] << 8) | this[offset + 1]
- }
- Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ((this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16)) +
- (this[offset + 3] * 0x1000000)
- }
- Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
- return (this[offset] * 0x1000000) +
- ((this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- this[offset + 3])
- }
- Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
- mul *= 0x80
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
- return val
- }
- Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
- var i = byteLength
- var mul = 1
- var val = this[offset + --i]
- while (i > 0 && (mul *= 0x100)) {
- val += this[offset + --i] * mul
- }
- mul *= 0x80
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
- return val
- }
- Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 1, this.length)
- if (!(this[offset] & 0x80)) return (this[offset])
- return ((0xff - this[offset] + 1) * -1)
- }
- Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset] | (this[offset + 1] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
- }
- Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset + 1] | (this[offset] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
- }
- Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
- return (this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16) |
- (this[offset + 3] << 24)
- }
- Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
- return (this[offset] << 24) |
- (this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- (this[offset + 3])
- }
- Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, true, 23, 4)
- }
- Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, false, 23, 4)
- }
- Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, true, 52, 8)
- }
- Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, false, 52, 8)
- }
- function checkInt (buf, value, offset, ext, max, min) {
- if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
- }
- Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1
- checkInt(this, value, offset, byteLength, maxBytes, 0)
- }
- var mul = 1
- var i = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- byteLength = byteLength >>> 0
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1
- checkInt(this, value, offset, byteLength, maxBytes, 0)
- }
- var i = byteLength - 1
- var mul = 1
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
- this[offset] = (value & 0xff)
- return offset + 1
- }
- Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- return offset + 2
- }
- Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- return offset + 2
- }
- Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- this[offset + 3] = (value >>> 24)
- this[offset + 2] = (value >>> 16)
- this[offset + 1] = (value >>> 8)
- this[offset] = (value & 0xff)
- return offset + 4
- }
- Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- return offset + 4
- }
- Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- var limit = Math.pow(2, (8 * byteLength) - 1)
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
- var i = 0
- var mul = 1
- var sub = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
- sub = 1
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- var limit = Math.pow(2, (8 * byteLength) - 1)
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
- var i = byteLength - 1
- var mul = 1
- var sub = 0
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
- sub = 1
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
- if (value < 0) value = 0xff + value + 1
- this[offset] = (value & 0xff)
- return offset + 1
- }
- Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- return offset + 2
- }
- Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- return offset + 2
- }
- Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- this[offset + 2] = (value >>> 16)
- this[offset + 3] = (value >>> 24)
- return offset + 4
- }
- Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- if (value < 0) value = 0xffffffff + value + 1
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- return offset + 4
- }
- function checkIEEE754 (buf, value, offset, ext, max, min) {
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
- if (offset < 0) throw new RangeError('Index out of range')
- }
- function writeFloat (buf, value, offset, littleEndian, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
- }
- ieee754.write(buf, value, offset, littleEndian, 23, 4)
- return offset + 4
- }
- Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
- return writeFloat(this, value, offset, true, noAssert)
- }
- Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
- return writeFloat(this, value, offset, false, noAssert)
- }
- function writeDouble (buf, value, offset, littleEndian, noAssert) {
- value = +value
- offset = offset >>> 0
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
- }
- ieee754.write(buf, value, offset, littleEndian, 52, 8)
- return offset + 8
- }
- Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
- return writeDouble(this, value, offset, true, noAssert)
- }
- Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
- return writeDouble(this, value, offset, false, noAssert)
- }
- // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
- Buffer.prototype.copy = function copy (target, targetStart, start, end) {
- if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
- if (!start) start = 0
- if (!end && end !== 0) end = this.length
- if (targetStart >= target.length) targetStart = target.length
- if (!targetStart) targetStart = 0
- if (end > 0 && end < start) end = start
- // Copy 0 bytes; we're done
- if (end === start) return 0
- if (target.length === 0 || this.length === 0) return 0
- // Fatal error conditions
- if (targetStart < 0) {
- throw new RangeError('targetStart out of bounds')
- }
- if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
- // Are we oob?
- if (end > this.length) end = this.length
- if (target.length - targetStart < end - start) {
- end = target.length - targetStart + start
- }
- var len = end - start
- if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
- // Use built-in when available, missing from IE11
- this.copyWithin(targetStart, start, end)
- } else if (this === target && start < targetStart && targetStart < end) {
- // descending copy from end
- for (var i = len - 1; i >= 0; --i) {
- target[i + targetStart] = this[i + start]
- }
- } else {
- Uint8Array.prototype.set.call(
- target,
- this.subarray(start, end),
- targetStart
- )
- }
- return len
- }
- // Usage:
- // buffer.fill(number[, offset[, end]])
- // buffer.fill(buffer[, offset[, end]])
- // buffer.fill(string[, offset[, end]][, encoding])
- Buffer.prototype.fill = function fill (val, start, end, encoding) {
- // Handle string cases:
- if (typeof val === 'string') {
- if (typeof start === 'string') {
- encoding = start
- start = 0
- end = this.length
- } else if (typeof end === 'string') {
- encoding = end
- end = this.length
- }
- if (encoding !== undefined && typeof encoding !== 'string') {
- throw new TypeError('encoding must be a string')
- }
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
- throw new TypeError('Unknown encoding: ' + encoding)
- }
- if (val.length === 1) {
- var code = val.charCodeAt(0)
- if ((encoding === 'utf8' && code < 128) ||
- encoding === 'latin1') {
- // Fast path: If `val` fits into a single byte, use that numeric value.
- val = code
- }
- }
- } else if (typeof val === 'number') {
- val = val & 255
- } else if (typeof val === 'boolean') {
- val = Number(val)
- }
- // Invalid ranges are not set to a default, so can range check early.
- if (start < 0 || this.length < start || this.length < end) {
- throw new RangeError('Out of range index')
- }
- if (end <= start) {
- return this
- }
- start = start >>> 0
- end = end === undefined ? this.length : end >>> 0
- if (!val) val = 0
- var i
- if (typeof val === 'number') {
- for (i = start; i < end; ++i) {
- this[i] = val
- }
- } else {
- var bytes = Buffer.isBuffer(val)
- ? val
- : Buffer.from(val, encoding)
- var len = bytes.length
- if (len === 0) {
- throw new TypeError('The value "' + val +
- '" is invalid for argument "value"')
- }
- for (i = 0; i < end - start; ++i) {
- this[i + start] = bytes[i % len]
- }
- }
- return this
- }
- // HELPER FUNCTIONS
- // ================
- var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
- function base64clean (str) {
- // Node takes equal signs as end of the Base64 encoding
- str = str.split('=')[0]
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
- str = str.trim().replace(INVALID_BASE64_RE, '')
- // Node converts strings with length < 2 to ''
- if (str.length < 2) return ''
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
- while (str.length % 4 !== 0) {
- str = str + '='
- }
- return str
- }
- function utf8ToBytes (string, units) {
- units = units || Infinity
- var codePoint
- var length = string.length
- var leadSurrogate = null
- var bytes = []
- for (var i = 0; i < length; ++i) {
- codePoint = string.charCodeAt(i)
- // is surrogate component
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
- // last char was a lead
- if (!leadSurrogate) {
- // no lead yet
- if (codePoint > 0xDBFF) {
- // unexpected trail
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- } else if (i + 1 === length) {
- // unpaired lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- }
- // valid lead
- leadSurrogate = codePoint
- continue
- }
- // 2 leads in a row
- if (codePoint < 0xDC00) {
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- leadSurrogate = codePoint
- continue
- }
- // valid surrogate pair
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
- } else if (leadSurrogate) {
- // valid bmp char, but last char was a lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- }
- leadSurrogate = null
- // encode utf8
- if (codePoint < 0x80) {
- if ((units -= 1) < 0) break
- bytes.push(codePoint)
- } else if (codePoint < 0x800) {
- if ((units -= 2) < 0) break
- bytes.push(
- codePoint >> 0x6 | 0xC0,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x10000) {
- if ((units -= 3) < 0) break
- bytes.push(
- codePoint >> 0xC | 0xE0,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x110000) {
- if ((units -= 4) < 0) break
- bytes.push(
- codePoint >> 0x12 | 0xF0,
- codePoint >> 0xC & 0x3F | 0x80,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else {
- throw new Error('Invalid code point')
- }
- }
- return bytes
- }
- function asciiToBytes (str) {
- var byteArray = []
- for (var i = 0; i < str.length; ++i) {
- // Node's code seems to be doing this and not & 0x7F..
- byteArray.push(str.charCodeAt(i) & 0xFF)
- }
- return byteArray
- }
- function utf16leToBytes (str, units) {
- var c, hi, lo
- var byteArray = []
- for (var i = 0; i < str.length; ++i) {
- if ((units -= 2) < 0) break
- c = str.charCodeAt(i)
- hi = c >> 8
- lo = c % 256
- byteArray.push(lo)
- byteArray.push(hi)
- }
- return byteArray
- }
- function base64ToBytes (str) {
- return base64.toByteArray(base64clean(str))
- }
- function blitBuffer (src, dst, offset, length) {
- for (var i = 0; i < length; ++i) {
- if ((i + offset >= dst.length) || (i >= src.length)) break
- dst[i + offset] = src[i]
- }
- return i
- }
- // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
- // the `instanceof` check but they should be treated as of that type.
- // See: https://github.com/feross/buffer/issues/166
- function isInstance (obj, type) {
- return obj instanceof type ||
- (obj != null && obj.constructor != null && obj.constructor.name != null &&
- obj.constructor.name === type.name)
- }
- function numberIsNaN (obj) {
- // For IE11 support
- return obj !== obj // eslint-disable-line no-self-compare
- }
- // Create lookup table for `toString('hex')`
- // See: https://github.com/feross/buffer/issues/219
- var hexSliceLookupTable = (function () {
- var alphabet = '0123456789abcdef'
- var table = new Array(256)
- for (var i = 0; i < 16; ++i) {
- var i16 = i * 16
- for (var j = 0; j < 16; ++j) {
- table[i16 + j] = alphabet[i] + alphabet[j]
- }
- }
- return table
- })()
- }).call(this,require("buffer").Buffer)
- },{"base64-js":28,"buffer":47,"ieee754":253}],48:[function(require,module,exports){
- var Buffer = require('buffer').Buffer; // for use with browserify
- module.exports = function (a, b) {
- if (!Buffer.isBuffer(a)) return undefined;
- if (!Buffer.isBuffer(b)) return undefined;
- if (typeof a.equals === 'function') return a.equals(b);
- if (a.length !== b.length) return false;
-
- for (var i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) return false;
- }
-
- return true;
- };
- },{"buffer":47}],49:[function(require,module,exports){
- module.exports = {
- "100": "Continue",
- "101": "Switching Protocols",
- "102": "Processing",
- "200": "OK",
- "201": "Created",
- "202": "Accepted",
- "203": "Non-Authoritative Information",
- "204": "No Content",
- "205": "Reset Content",
- "206": "Partial Content",
- "207": "Multi-Status",
- "208": "Already Reported",
- "226": "IM Used",
- "300": "Multiple Choices",
- "301": "Moved Permanently",
- "302": "Found",
- "303": "See Other",
- "304": "Not Modified",
- "305": "Use Proxy",
- "307": "Temporary Redirect",
- "308": "Permanent Redirect",
- "400": "Bad Request",
- "401": "Unauthorized",
- "402": "Payment Required",
- "403": "Forbidden",
- "404": "Not Found",
- "405": "Method Not Allowed",
- "406": "Not Acceptable",
- "407": "Proxy Authentication Required",
- "408": "Request Timeout",
- "409": "Conflict",
- "410": "Gone",
- "411": "Length Required",
- "412": "Precondition Failed",
- "413": "Payload Too Large",
- "414": "URI Too Long",
- "415": "Unsupported Media Type",
- "416": "Range Not Satisfiable",
- "417": "Expectation Failed",
- "418": "I'm a teapot",
- "421": "Misdirected Request",
- "422": "Unprocessable Entity",
- "423": "Locked",
- "424": "Failed Dependency",
- "425": "Unordered Collection",
- "426": "Upgrade Required",
- "428": "Precondition Required",
- "429": "Too Many Requests",
- "431": "Request Header Fields Too Large",
- "451": "Unavailable For Legal Reasons",
- "500": "Internal Server Error",
- "501": "Not Implemented",
- "502": "Bad Gateway",
- "503": "Service Unavailable",
- "504": "Gateway Timeout",
- "505": "HTTP Version Not Supported",
- "506": "Variant Also Negotiates",
- "507": "Insufficient Storage",
- "508": "Loop Detected",
- "509": "Bandwidth Limit Exceeded",
- "510": "Not Extended",
- "511": "Network Authentication Required"
- }
- },{}],50:[function(require,module,exports){
- module.exports = function (it) {
- if (typeof it != 'function') {
- throw TypeError(String(it) + ' is not a function');
- } return it;
- };
- },{}],51:[function(require,module,exports){
- var isObject = require('../internals/is-object');
- module.exports = function (it) {
- if (!isObject(it) && it !== null) {
- throw TypeError("Can't set " + String(it) + ' as a prototype');
- } return it;
- };
- },{"../internals/is-object":105}],52:[function(require,module,exports){
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var create = require('../internals/object-create');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var UNSCOPABLES = wellKnownSymbol('unscopables');
- var ArrayPrototype = Array.prototype;
- // Array.prototype[@@unscopables]
- // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
- if (ArrayPrototype[UNSCOPABLES] == undefined) {
- createNonEnumerableProperty(ArrayPrototype, UNSCOPABLES, create(null));
- }
- // add a key to Array.prototype[@@unscopables]
- module.exports = function (key) {
- ArrayPrototype[UNSCOPABLES][key] = true;
- };
- },{"../internals/create-non-enumerable-property":76,"../internals/object-create":118,"../internals/well-known-symbol":169}],53:[function(require,module,exports){
- 'use strict';
- var charAt = require('../internals/string-multibyte').charAt;
- // `AdvanceStringIndex` abstract operation
- // https://tc39.github.io/ecma262/#sec-advancestringindex
- module.exports = function (S, index, unicode) {
- return index + (unicode ? charAt(S, index).length : 1);
- };
- },{"../internals/string-multibyte":151}],54:[function(require,module,exports){
- module.exports = function (it, Constructor, name) {
- if (!(it instanceof Constructor)) {
- throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation');
- } return it;
- };
- },{}],55:[function(require,module,exports){
- var isObject = require('../internals/is-object');
- module.exports = function (it) {
- if (!isObject(it)) {
- throw TypeError(String(it) + ' is not an object');
- } return it;
- };
- },{"../internals/is-object":105}],56:[function(require,module,exports){
- 'use strict';
- var DESCRIPTORS = require('../internals/descriptors');
- var global = require('../internals/global');
- var isObject = require('../internals/is-object');
- var has = require('../internals/has');
- var classof = require('../internals/classof');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var redefine = require('../internals/redefine');
- var defineProperty = require('../internals/object-define-property').f;
- var getPrototypeOf = require('../internals/object-get-prototype-of');
- var setPrototypeOf = require('../internals/object-set-prototype-of');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var uid = require('../internals/uid');
- var DataView = global.DataView;
- var DataViewPrototype = DataView && DataView.prototype;
- var Int8Array = global.Int8Array;
- var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
- var Uint8ClampedArray = global.Uint8ClampedArray;
- var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
- var TypedArray = Int8Array && getPrototypeOf(Int8Array);
- var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);
- var ObjectPrototype = Object.prototype;
- var isPrototypeOf = ObjectPrototype.isPrototypeOf;
- var TO_STRING_TAG = wellKnownSymbol('toStringTag');
- var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');
- var NATIVE_ARRAY_BUFFER = !!(global.ArrayBuffer && DataView);
- // Fixing native typed arrays in Opera Presto crashes the browser, see #595
- var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';
- var TYPED_ARRAY_TAG_REQIRED = false;
- var NAME;
- var TypedArrayConstructorsList = {
- Int8Array: 1,
- Uint8Array: 1,
- Uint8ClampedArray: 1,
- Int16Array: 2,
- Uint16Array: 2,
- Int32Array: 4,
- Uint32Array: 4,
- Float32Array: 4,
- Float64Array: 8
- };
- var isView = function isView(it) {
- var klass = classof(it);
- return klass === 'DataView' || has(TypedArrayConstructorsList, klass);
- };
- var isTypedArray = function (it) {
- return isObject(it) && has(TypedArrayConstructorsList, classof(it));
- };
- var aTypedArray = function (it) {
- if (isTypedArray(it)) return it;
- throw TypeError('Target is not a typed array');
- };
- var aTypedArrayConstructor = function (C) {
- if (setPrototypeOf) {
- if (isPrototypeOf.call(TypedArray, C)) return C;
- } else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME)) {
- var TypedArrayConstructor = global[ARRAY];
- if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) {
- return C;
- }
- } throw TypeError('Target is not a typed array constructor');
- };
- var exportProto = function (KEY, property, forced) {
- if (!DESCRIPTORS) return;
- if (forced) for (var ARRAY in TypedArrayConstructorsList) {
- var TypedArrayConstructor = global[ARRAY];
- if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) {
- delete TypedArrayConstructor.prototype[KEY];
- }
- }
- if (!TypedArrayPrototype[KEY] || forced) {
- redefine(TypedArrayPrototype, KEY, forced ? property
- : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property);
- }
- };
- var exportStatic = function (KEY, property, forced) {
- var ARRAY, TypedArrayConstructor;
- if (!DESCRIPTORS) return;
- if (setPrototypeOf) {
- if (forced) for (ARRAY in TypedArrayConstructorsList) {
- TypedArrayConstructor = global[ARRAY];
- if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) {
- delete TypedArrayConstructor[KEY];
- }
- }
- if (!TypedArray[KEY] || forced) {
- // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
- try {
- return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property);
- } catch (error) { /* empty */ }
- } else return;
- }
- for (ARRAY in TypedArrayConstructorsList) {
- TypedArrayConstructor = global[ARRAY];
- if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
- redefine(TypedArrayConstructor, KEY, property);
- }
- }
- };
- for (NAME in TypedArrayConstructorsList) {
- if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false;
- }
- // WebKit bug - typed arrays constructors prototype is Object.prototype
- if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) {
- // eslint-disable-next-line no-shadow
- TypedArray = function TypedArray() {
- throw TypeError('Incorrect invocation');
- };
- if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
- if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);
- }
- }
- if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {
- TypedArrayPrototype = TypedArray.prototype;
- if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
- if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);
- }
- }
- // WebKit bug - one more object in Uint8ClampedArray prototype chain
- if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
- setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
- }
- if (DESCRIPTORS && !has(TypedArrayPrototype, TO_STRING_TAG)) {
- TYPED_ARRAY_TAG_REQIRED = true;
- defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () {
- return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;
- } });
- for (NAME in TypedArrayConstructorsList) if (global[NAME]) {
- createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);
- }
- }
- // WebKit bug - the same parent prototype for typed arrays and data view
- if (NATIVE_ARRAY_BUFFER && setPrototypeOf && getPrototypeOf(DataViewPrototype) !== ObjectPrototype) {
- setPrototypeOf(DataViewPrototype, ObjectPrototype);
- }
- module.exports = {
- NATIVE_ARRAY_BUFFER: NATIVE_ARRAY_BUFFER,
- NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,
- TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG,
- aTypedArray: aTypedArray,
- aTypedArrayConstructor: aTypedArrayConstructor,
- exportProto: exportProto,
- exportStatic: exportStatic,
- isView: isView,
- isTypedArray: isTypedArray,
- TypedArray: TypedArray,
- TypedArrayPrototype: TypedArrayPrototype
- };
- },{"../internals/classof":71,"../internals/create-non-enumerable-property":76,"../internals/descriptors":81,"../internals/global":92,"../internals/has":93,"../internals/is-object":105,"../internals/object-define-property":120,"../internals/object-get-prototype-of":125,"../internals/object-set-prototype-of":129,"../internals/redefine":138,"../internals/uid":166,"../internals/well-known-symbol":169}],57:[function(require,module,exports){
- 'use strict';
- var global = require('../internals/global');
- var DESCRIPTORS = require('../internals/descriptors');
- var NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-view-core').NATIVE_ARRAY_BUFFER;
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var redefineAll = require('../internals/redefine-all');
- var fails = require('../internals/fails');
- var anInstance = require('../internals/an-instance');
- var toInteger = require('../internals/to-integer');
- var toLength = require('../internals/to-length');
- var toIndex = require('../internals/to-index');
- var getOwnPropertyNames = require('../internals/object-get-own-property-names').f;
- var defineProperty = require('../internals/object-define-property').f;
- var arrayFill = require('../internals/array-fill');
- var setToStringTag = require('../internals/set-to-string-tag');
- var InternalStateModule = require('../internals/internal-state');
- var getInternalState = InternalStateModule.get;
- var setInternalState = InternalStateModule.set;
- var ARRAY_BUFFER = 'ArrayBuffer';
- var DATA_VIEW = 'DataView';
- var PROTOTYPE = 'prototype';
- var WRONG_LENGTH = 'Wrong length';
- var WRONG_INDEX = 'Wrong index';
- var NativeArrayBuffer = global[ARRAY_BUFFER];
- var $ArrayBuffer = NativeArrayBuffer;
- var $DataView = global[DATA_VIEW];
- var Math = global.Math;
- var RangeError = global.RangeError;
- // eslint-disable-next-line no-shadow-restricted-names
- var Infinity = 1 / 0;
- var abs = Math.abs;
- var pow = Math.pow;
- var floor = Math.floor;
- var log = Math.log;
- var LN2 = Math.LN2;
- // IEEE754 conversions based on https://github.com/feross/ieee754
- var packIEEE754 = function (number, mantissaLength, bytes) {
- var buffer = new Array(bytes);
- var exponentLength = bytes * 8 - mantissaLength - 1;
- var eMax = (1 << exponentLength) - 1;
- var eBias = eMax >> 1;
- var rt = mantissaLength === 23 ? pow(2, -24) - pow(2, -77) : 0;
- var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0;
- var index = 0;
- var exponent, mantissa, c;
- number = abs(number);
- // eslint-disable-next-line no-self-compare
- if (number != number || number === Infinity) {
- // eslint-disable-next-line no-self-compare
- mantissa = number != number ? 1 : 0;
- exponent = eMax;
- } else {
- exponent = floor(log(number) / LN2);
- if (number * (c = pow(2, -exponent)) < 1) {
- exponent--;
- c *= 2;
- }
- if (exponent + eBias >= 1) {
- number += rt / c;
- } else {
- number += rt * pow(2, 1 - eBias);
- }
- if (number * c >= 2) {
- exponent++;
- c /= 2;
- }
- if (exponent + eBias >= eMax) {
- mantissa = 0;
- exponent = eMax;
- } else if (exponent + eBias >= 1) {
- mantissa = (number * c - 1) * pow(2, mantissaLength);
- exponent = exponent + eBias;
- } else {
- mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength);
- exponent = 0;
- }
- }
- for (; mantissaLength >= 8; buffer[index++] = mantissa & 255, mantissa /= 256, mantissaLength -= 8);
- exponent = exponent << mantissaLength | mantissa;
- exponentLength += mantissaLength;
- for (; exponentLength > 0; buffer[index++] = exponent & 255, exponent /= 256, exponentLength -= 8);
- buffer[--index] |= sign * 128;
- return buffer;
- };
- var unpackIEEE754 = function (buffer, mantissaLength) {
- var bytes = buffer.length;
- var exponentLength = bytes * 8 - mantissaLength - 1;
- var eMax = (1 << exponentLength) - 1;
- var eBias = eMax >> 1;
- var nBits = exponentLength - 7;
- var index = bytes - 1;
- var sign = buffer[index--];
- var exponent = sign & 127;
- var mantissa;
- sign >>= 7;
- for (; nBits > 0; exponent = exponent * 256 + buffer[index], index--, nBits -= 8);
- mantissa = exponent & (1 << -nBits) - 1;
- exponent >>= -nBits;
- nBits += mantissaLength;
- for (; nBits > 0; mantissa = mantissa * 256 + buffer[index], index--, nBits -= 8);
- if (exponent === 0) {
- exponent = 1 - eBias;
- } else if (exponent === eMax) {
- return mantissa ? NaN : sign ? -Infinity : Infinity;
- } else {
- mantissa = mantissa + pow(2, mantissaLength);
- exponent = exponent - eBias;
- } return (sign ? -1 : 1) * mantissa * pow(2, exponent - mantissaLength);
- };
- var unpackInt32 = function (buffer) {
- return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
- };
- var packInt8 = function (number) {
- return [number & 0xFF];
- };
- var packInt16 = function (number) {
- return [number & 0xFF, number >> 8 & 0xFF];
- };
- var packInt32 = function (number) {
- return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF];
- };
- var packFloat32 = function (number) {
- return packIEEE754(number, 23, 4);
- };
- var packFloat64 = function (number) {
- return packIEEE754(number, 52, 8);
- };
- var addGetter = function (Constructor, key) {
- defineProperty(Constructor[PROTOTYPE], key, { get: function () { return getInternalState(this)[key]; } });
- };
- var get = function (view, count, index, isLittleEndian) {
- var numIndex = +index;
- var intIndex = toIndex(numIndex);
- var store = getInternalState(view);
- if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX);
- var bytes = getInternalState(store.buffer).bytes;
- var start = intIndex + store.byteOffset;
- var pack = bytes.slice(start, start + count);
- return isLittleEndian ? pack : pack.reverse();
- };
- var set = function (view, count, index, conversion, value, isLittleEndian) {
- var numIndex = +index;
- var intIndex = toIndex(numIndex);
- var store = getInternalState(view);
- if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX);
- var bytes = getInternalState(store.buffer).bytes;
- var start = intIndex + store.byteOffset;
- var pack = conversion(+value);
- for (var i = 0; i < count; i++) bytes[start + i] = pack[isLittleEndian ? i : count - i - 1];
- };
- if (!NATIVE_ARRAY_BUFFER) {
- $ArrayBuffer = function ArrayBuffer(length) {
- anInstance(this, $ArrayBuffer, ARRAY_BUFFER);
- var byteLength = toIndex(length);
- setInternalState(this, {
- bytes: arrayFill.call(new Array(byteLength), 0),
- byteLength: byteLength
- });
- if (!DESCRIPTORS) this.byteLength = byteLength;
- };
- $DataView = function DataView(buffer, byteOffset, byteLength) {
- anInstance(this, $DataView, DATA_VIEW);
- anInstance(buffer, $ArrayBuffer, DATA_VIEW);
- var bufferLength = getInternalState(buffer).byteLength;
- var offset = toInteger(byteOffset);
- if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset');
- byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
- if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH);
- setInternalState(this, {
- buffer: buffer,
- byteLength: byteLength,
- byteOffset: offset
- });
- if (!DESCRIPTORS) {
- this.buffer = buffer;
- this.byteLength = byteLength;
- this.byteOffset = offset;
- }
- };
- if (DESCRIPTORS) {
- addGetter($ArrayBuffer, 'byteLength');
- addGetter($DataView, 'buffer');
- addGetter($DataView, 'byteLength');
- addGetter($DataView, 'byteOffset');
- }
- redefineAll($DataView[PROTOTYPE], {
- getInt8: function getInt8(byteOffset) {
- return get(this, 1, byteOffset)[0] << 24 >> 24;
- },
- getUint8: function getUint8(byteOffset) {
- return get(this, 1, byteOffset)[0];
- },
- getInt16: function getInt16(byteOffset /* , littleEndian */) {
- var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined);
- return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
- },
- getUint16: function getUint16(byteOffset /* , littleEndian */) {
- var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined);
- return bytes[1] << 8 | bytes[0];
- },
- getInt32: function getInt32(byteOffset /* , littleEndian */) {
- return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined));
- },
- getUint32: function getUint32(byteOffset /* , littleEndian */) {
- return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0;
- },
- getFloat32: function getFloat32(byteOffset /* , littleEndian */) {
- return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23);
- },
- getFloat64: function getFloat64(byteOffset /* , littleEndian */) {
- return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52);
- },
- setInt8: function setInt8(byteOffset, value) {
- set(this, 1, byteOffset, packInt8, value);
- },
- setUint8: function setUint8(byteOffset, value) {
- set(this, 1, byteOffset, packInt8, value);
- },
- setInt16: function setInt16(byteOffset, value /* , littleEndian */) {
- set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined);
- },
- setUint16: function setUint16(byteOffset, value /* , littleEndian */) {
- set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined);
- },
- setInt32: function setInt32(byteOffset, value /* , littleEndian */) {
- set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined);
- },
- setUint32: function setUint32(byteOffset, value /* , littleEndian */) {
- set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined);
- },
- setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) {
- set(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined);
- },
- setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) {
- set(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined);
- }
- });
- } else {
- if (!fails(function () {
- NativeArrayBuffer(1);
- }) || !fails(function () {
- new NativeArrayBuffer(-1); // eslint-disable-line no-new
- }) || fails(function () {
- new NativeArrayBuffer(); // eslint-disable-line no-new
- new NativeArrayBuffer(1.5); // eslint-disable-line no-new
- new NativeArrayBuffer(NaN); // eslint-disable-line no-new
- return NativeArrayBuffer.name != ARRAY_BUFFER;
- })) {
- $ArrayBuffer = function ArrayBuffer(length) {
- anInstance(this, $ArrayBuffer);
- return new NativeArrayBuffer(toIndex(length));
- };
- var ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE] = NativeArrayBuffer[PROTOTYPE];
- for (var keys = getOwnPropertyNames(NativeArrayBuffer), j = 0, key; keys.length > j;) {
- if (!((key = keys[j++]) in $ArrayBuffer)) {
- createNonEnumerableProperty($ArrayBuffer, key, NativeArrayBuffer[key]);
- }
- }
- ArrayBufferPrototype.constructor = $ArrayBuffer;
- }
- // iOS Safari 7.x bug
- var testView = new $DataView(new $ArrayBuffer(2));
- var nativeSetInt8 = $DataView[PROTOTYPE].setInt8;
- testView.setInt8(0, 2147483648);
- testView.setInt8(1, 2147483649);
- if (testView.getInt8(0) || !testView.getInt8(1)) redefineAll($DataView[PROTOTYPE], {
- setInt8: function setInt8(byteOffset, value) {
- nativeSetInt8.call(this, byteOffset, value << 24 >> 24);
- },
- setUint8: function setUint8(byteOffset, value) {
- nativeSetInt8.call(this, byteOffset, value << 24 >> 24);
- }
- }, { unsafe: true });
- }
- setToStringTag($ArrayBuffer, ARRAY_BUFFER);
- setToStringTag($DataView, DATA_VIEW);
- module.exports = {
- ArrayBuffer: $ArrayBuffer,
- DataView: $DataView
- };
- },{"../internals/an-instance":54,"../internals/array-buffer-view-core":56,"../internals/array-fill":59,"../internals/create-non-enumerable-property":76,"../internals/descriptors":81,"../internals/fails":86,"../internals/global":92,"../internals/internal-state":100,"../internals/object-define-property":120,"../internals/object-get-own-property-names":123,"../internals/redefine-all":137,"../internals/set-to-string-tag":145,"../internals/to-index":155,"../internals/to-integer":157,"../internals/to-length":158}],58:[function(require,module,exports){
- 'use strict';
- var toObject = require('../internals/to-object');
- var toAbsoluteIndex = require('../internals/to-absolute-index');
- var toLength = require('../internals/to-length');
- var min = Math.min;
- // `Array.prototype.copyWithin` method implementation
- // https://tc39.github.io/ecma262/#sec-array.prototype.copywithin
- module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
- var O = toObject(this);
- var len = toLength(O.length);
- var to = toAbsoluteIndex(target, len);
- var from = toAbsoluteIndex(start, len);
- var end = arguments.length > 2 ? arguments[2] : undefined;
- var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
- var inc = 1;
- if (from < to && to < from + count) {
- inc = -1;
- from += count - 1;
- to += count - 1;
- }
- while (count-- > 0) {
- if (from in O) O[to] = O[from];
- else delete O[to];
- to += inc;
- from += inc;
- } return O;
- };
- },{"../internals/to-absolute-index":154,"../internals/to-length":158,"../internals/to-object":159}],59:[function(require,module,exports){
- 'use strict';
- var toObject = require('../internals/to-object');
- var toAbsoluteIndex = require('../internals/to-absolute-index');
- var toLength = require('../internals/to-length');
- // `Array.prototype.fill` method implementation
- // https://tc39.github.io/ecma262/#sec-array.prototype.fill
- module.exports = function fill(value /* , start = 0, end = @length */) {
- var O = toObject(this);
- var length = toLength(O.length);
- var argumentsLength = arguments.length;
- var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length);
- var end = argumentsLength > 2 ? arguments[2] : undefined;
- var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
- while (endPos > index) O[index++] = value;
- return O;
- };
- },{"../internals/to-absolute-index":154,"../internals/to-length":158,"../internals/to-object":159}],60:[function(require,module,exports){
- 'use strict';
- var $forEach = require('../internals/array-iteration').forEach;
- var sloppyArrayMethod = require('../internals/sloppy-array-method');
- // `Array.prototype.forEach` method implementation
- // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
- module.exports = sloppyArrayMethod('forEach') ? function forEach(callbackfn /* , thisArg */) {
- return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
- } : [].forEach;
- },{"../internals/array-iteration":62,"../internals/sloppy-array-method":149}],61:[function(require,module,exports){
- var toIndexedObject = require('../internals/to-indexed-object');
- var toLength = require('../internals/to-length');
- var toAbsoluteIndex = require('../internals/to-absolute-index');
- // `Array.prototype.{ indexOf, includes }` methods implementation
- var createMethod = function (IS_INCLUDES) {
- return function ($this, el, fromIndex) {
- var O = toIndexedObject($this);
- var length = toLength(O.length);
- var index = toAbsoluteIndex(fromIndex, length);
- var value;
- // Array#includes uses SameValueZero equality algorithm
- // eslint-disable-next-line no-self-compare
- if (IS_INCLUDES && el != el) while (length > index) {
- value = O[index++];
- // eslint-disable-next-line no-self-compare
- if (value != value) return true;
- // Array#indexOf ignores holes, Array#includes - not
- } else for (;length > index; index++) {
- if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
- } return !IS_INCLUDES && -1;
- };
- };
- module.exports = {
- // `Array.prototype.includes` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.includes
- includes: createMethod(true),
- // `Array.prototype.indexOf` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.indexof
- indexOf: createMethod(false)
- };
- },{"../internals/to-absolute-index":154,"../internals/to-indexed-object":156,"../internals/to-length":158}],62:[function(require,module,exports){
- var bind = require('../internals/bind-context');
- var IndexedObject = require('../internals/indexed-object');
- var toObject = require('../internals/to-object');
- var toLength = require('../internals/to-length');
- var arraySpeciesCreate = require('../internals/array-species-create');
- var push = [].push;
- // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation
- var createMethod = function (TYPE) {
- var IS_MAP = TYPE == 1;
- var IS_FILTER = TYPE == 2;
- var IS_SOME = TYPE == 3;
- var IS_EVERY = TYPE == 4;
- var IS_FIND_INDEX = TYPE == 6;
- var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
- return function ($this, callbackfn, that, specificCreate) {
- var O = toObject($this);
- var self = IndexedObject(O);
- var boundFunction = bind(callbackfn, that, 3);
- var length = toLength(self.length);
- var index = 0;
- var create = specificCreate || arraySpeciesCreate;
- var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
- var value, result;
- for (;length > index; index++) if (NO_HOLES || index in self) {
- value = self[index];
- result = boundFunction(value, index, O);
- if (TYPE) {
- if (IS_MAP) target[index] = result; // map
- else if (result) switch (TYPE) {
- case 3: return true; // some
- case 5: return value; // find
- case 6: return index; // findIndex
- case 2: push.call(target, value); // filter
- } else if (IS_EVERY) return false; // every
- }
- }
- return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
- };
- };
- module.exports = {
- // `Array.prototype.forEach` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
- forEach: createMethod(0),
- // `Array.prototype.map` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.map
- map: createMethod(1),
- // `Array.prototype.filter` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.filter
- filter: createMethod(2),
- // `Array.prototype.some` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.some
- some: createMethod(3),
- // `Array.prototype.every` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.every
- every: createMethod(4),
- // `Array.prototype.find` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.find
- find: createMethod(5),
- // `Array.prototype.findIndex` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
- findIndex: createMethod(6)
- };
- },{"../internals/array-species-create":66,"../internals/bind-context":67,"../internals/indexed-object":98,"../internals/to-length":158,"../internals/to-object":159}],63:[function(require,module,exports){
- 'use strict';
- var toIndexedObject = require('../internals/to-indexed-object');
- var toInteger = require('../internals/to-integer');
- var toLength = require('../internals/to-length');
- var sloppyArrayMethod = require('../internals/sloppy-array-method');
- var min = Math.min;
- var nativeLastIndexOf = [].lastIndexOf;
- var NEGATIVE_ZERO = !!nativeLastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0;
- var SLOPPY_METHOD = sloppyArrayMethod('lastIndexOf');
- // `Array.prototype.lastIndexOf` method implementation
- // https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof
- module.exports = (NEGATIVE_ZERO || SLOPPY_METHOD) ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
- // convert -0 to +0
- if (NEGATIVE_ZERO) return nativeLastIndexOf.apply(this, arguments) || 0;
- var O = toIndexedObject(this);
- var length = toLength(O.length);
- var index = length - 1;
- if (arguments.length > 1) index = min(index, toInteger(arguments[1]));
- if (index < 0) index = length + index;
- for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;
- return -1;
- } : nativeLastIndexOf;
- },{"../internals/sloppy-array-method":149,"../internals/to-indexed-object":156,"../internals/to-integer":157,"../internals/to-length":158}],64:[function(require,module,exports){
- var fails = require('../internals/fails');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var V8_VERSION = require('../internals/v8-version');
- var SPECIES = wellKnownSymbol('species');
- module.exports = function (METHOD_NAME) {
- // We can't use this feature detection in V8 since it causes
- // deoptimization and serious performance degradation
- // https://github.com/zloirock/core-js/issues/677
- return V8_VERSION >= 51 || !fails(function () {
- var array = [];
- var constructor = array.constructor = {};
- constructor[SPECIES] = function () {
- return { foo: 1 };
- };
- return array[METHOD_NAME](Boolean).foo !== 1;
- });
- };
- },{"../internals/fails":86,"../internals/v8-version":168,"../internals/well-known-symbol":169}],65:[function(require,module,exports){
- var aFunction = require('../internals/a-function');
- var toObject = require('../internals/to-object');
- var IndexedObject = require('../internals/indexed-object');
- var toLength = require('../internals/to-length');
- // `Array.prototype.{ reduce, reduceRight }` methods implementation
- var createMethod = function (IS_RIGHT) {
- return function (that, callbackfn, argumentsLength, memo) {
- aFunction(callbackfn);
- var O = toObject(that);
- var self = IndexedObject(O);
- var length = toLength(O.length);
- var index = IS_RIGHT ? length - 1 : 0;
- var i = IS_RIGHT ? -1 : 1;
- if (argumentsLength < 2) while (true) {
- if (index in self) {
- memo = self[index];
- index += i;
- break;
- }
- index += i;
- if (IS_RIGHT ? index < 0 : length <= index) {
- throw TypeError('Reduce of empty array with no initial value');
- }
- }
- for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
- memo = callbackfn(memo, self[index], index, O);
- }
- return memo;
- };
- };
- module.exports = {
- // `Array.prototype.reduce` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.reduce
- left: createMethod(false),
- // `Array.prototype.reduceRight` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.reduceright
- right: createMethod(true)
- };
- },{"../internals/a-function":50,"../internals/indexed-object":98,"../internals/to-length":158,"../internals/to-object":159}],66:[function(require,module,exports){
- var isObject = require('../internals/is-object');
- var isArray = require('../internals/is-array');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var SPECIES = wellKnownSymbol('species');
- // `ArraySpeciesCreate` abstract operation
- // https://tc39.github.io/ecma262/#sec-arrayspeciescreate
- module.exports = function (originalArray, length) {
- var C;
- if (isArray(originalArray)) {
- C = originalArray.constructor;
- // cross-realm fallback
- if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
- else if (isObject(C)) {
- C = C[SPECIES];
- if (C === null) C = undefined;
- }
- } return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
- };
- },{"../internals/is-array":102,"../internals/is-object":105,"../internals/well-known-symbol":169}],67:[function(require,module,exports){
- var aFunction = require('../internals/a-function');
- // optional / simple context binding
- module.exports = function (fn, that, length) {
- aFunction(fn);
- if (that === undefined) return fn;
- switch (length) {
- case 0: return function () {
- return fn.call(that);
- };
- case 1: return function (a) {
- return fn.call(that, a);
- };
- case 2: return function (a, b) {
- return fn.call(that, a, b);
- };
- case 3: return function (a, b, c) {
- return fn.call(that, a, b, c);
- };
- }
- return function (/* ...args */) {
- return fn.apply(that, arguments);
- };
- };
- },{"../internals/a-function":50}],68:[function(require,module,exports){
- var anObject = require('../internals/an-object');
- // call something on iterator step with safe closing on error
- module.exports = function (iterator, fn, value, ENTRIES) {
- try {
- return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
- // 7.4.6 IteratorClose(iterator, completion)
- } catch (error) {
- var returnMethod = iterator['return'];
- if (returnMethod !== undefined) anObject(returnMethod.call(iterator));
- throw error;
- }
- };
- },{"../internals/an-object":55}],69:[function(require,module,exports){
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var ITERATOR = wellKnownSymbol('iterator');
- var SAFE_CLOSING = false;
- try {
- var called = 0;
- var iteratorWithReturn = {
- next: function () {
- return { done: !!called++ };
- },
- 'return': function () {
- SAFE_CLOSING = true;
- }
- };
- iteratorWithReturn[ITERATOR] = function () {
- return this;
- };
- // eslint-disable-next-line no-throw-literal
- Array.from(iteratorWithReturn, function () { throw 2; });
- } catch (error) { /* empty */ }
- module.exports = function (exec, SKIP_CLOSING) {
- if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
- var ITERATION_SUPPORT = false;
- try {
- var object = {};
- object[ITERATOR] = function () {
- return {
- next: function () {
- return { done: ITERATION_SUPPORT = true };
- }
- };
- };
- exec(object);
- } catch (error) { /* empty */ }
- return ITERATION_SUPPORT;
- };
- },{"../internals/well-known-symbol":169}],70:[function(require,module,exports){
- var toString = {}.toString;
- module.exports = function (it) {
- return toString.call(it).slice(8, -1);
- };
- },{}],71:[function(require,module,exports){
- var classofRaw = require('../internals/classof-raw');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var TO_STRING_TAG = wellKnownSymbol('toStringTag');
- // ES3 wrong here
- var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
- // fallback for IE11 Script Access Denied error
- var tryGet = function (it, key) {
- try {
- return it[key];
- } catch (error) { /* empty */ }
- };
- // getting tag from ES6+ `Object.prototype.toString`
- module.exports = function (it) {
- var O, tag, result;
- return it === undefined ? 'Undefined' : it === null ? 'Null'
- // @@toStringTag case
- : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag
- // builtinTag case
- : CORRECT_ARGUMENTS ? classofRaw(O)
- // ES3 arguments fallback
- : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
- };
- },{"../internals/classof-raw":70,"../internals/well-known-symbol":169}],72:[function(require,module,exports){
- var has = require('../internals/has');
- var ownKeys = require('../internals/own-keys');
- var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');
- var definePropertyModule = require('../internals/object-define-property');
- module.exports = function (target, source) {
- var keys = ownKeys(source);
- var defineProperty = definePropertyModule.f;
- var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
- }
- };
- },{"../internals/has":93,"../internals/object-define-property":120,"../internals/object-get-own-property-descriptor":121,"../internals/own-keys":132}],73:[function(require,module,exports){
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var MATCH = wellKnownSymbol('match');
- module.exports = function (METHOD_NAME) {
- var regexp = /./;
- try {
- '/./'[METHOD_NAME](regexp);
- } catch (e) {
- try {
- regexp[MATCH] = false;
- return '/./'[METHOD_NAME](regexp);
- } catch (f) { /* empty */ }
- } return false;
- };
- },{"../internals/well-known-symbol":169}],74:[function(require,module,exports){
- var fails = require('../internals/fails');
- module.exports = !fails(function () {
- function F() { /* empty */ }
- F.prototype.constructor = null;
- return Object.getPrototypeOf(new F()) !== F.prototype;
- });
- },{"../internals/fails":86}],75:[function(require,module,exports){
- 'use strict';
- var IteratorPrototype = require('../internals/iterators-core').IteratorPrototype;
- var create = require('../internals/object-create');
- var createPropertyDescriptor = require('../internals/create-property-descriptor');
- var setToStringTag = require('../internals/set-to-string-tag');
- var Iterators = require('../internals/iterators');
- var returnThis = function () { return this; };
- module.exports = function (IteratorConstructor, NAME, next) {
- var TO_STRING_TAG = NAME + ' Iterator';
- IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(1, next) });
- setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);
- Iterators[TO_STRING_TAG] = returnThis;
- return IteratorConstructor;
- };
- },{"../internals/create-property-descriptor":77,"../internals/iterators":110,"../internals/iterators-core":109,"../internals/object-create":118,"../internals/set-to-string-tag":145}],76:[function(require,module,exports){
- var DESCRIPTORS = require('../internals/descriptors');
- var definePropertyModule = require('../internals/object-define-property');
- var createPropertyDescriptor = require('../internals/create-property-descriptor');
- module.exports = DESCRIPTORS ? function (object, key, value) {
- return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
- } : function (object, key, value) {
- object[key] = value;
- return object;
- };
- },{"../internals/create-property-descriptor":77,"../internals/descriptors":81,"../internals/object-define-property":120}],77:[function(require,module,exports){
- module.exports = function (bitmap, value) {
- return {
- enumerable: !(bitmap & 1),
- configurable: !(bitmap & 2),
- writable: !(bitmap & 4),
- value: value
- };
- };
- },{}],78:[function(require,module,exports){
- 'use strict';
- var toPrimitive = require('../internals/to-primitive');
- var definePropertyModule = require('../internals/object-define-property');
- var createPropertyDescriptor = require('../internals/create-property-descriptor');
- module.exports = function (object, key, value) {
- var propertyKey = toPrimitive(key);
- if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value));
- else object[propertyKey] = value;
- };
- },{"../internals/create-property-descriptor":77,"../internals/object-define-property":120,"../internals/to-primitive":162}],79:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var createIteratorConstructor = require('../internals/create-iterator-constructor');
- var getPrototypeOf = require('../internals/object-get-prototype-of');
- var setPrototypeOf = require('../internals/object-set-prototype-of');
- var setToStringTag = require('../internals/set-to-string-tag');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var redefine = require('../internals/redefine');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var IS_PURE = require('../internals/is-pure');
- var Iterators = require('../internals/iterators');
- var IteratorsCore = require('../internals/iterators-core');
- var IteratorPrototype = IteratorsCore.IteratorPrototype;
- var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
- var ITERATOR = wellKnownSymbol('iterator');
- var KEYS = 'keys';
- var VALUES = 'values';
- var ENTRIES = 'entries';
- var returnThis = function () { return this; };
- module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
- createIteratorConstructor(IteratorConstructor, NAME, next);
- var getIterationMethod = function (KIND) {
- if (KIND === DEFAULT && defaultIterator) return defaultIterator;
- if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
- switch (KIND) {
- case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
- case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
- case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
- } return function () { return new IteratorConstructor(this); };
- };
- var TO_STRING_TAG = NAME + ' Iterator';
- var INCORRECT_VALUES_NAME = false;
- var IterablePrototype = Iterable.prototype;
- var nativeIterator = IterablePrototype[ITERATOR]
- || IterablePrototype['@@iterator']
- || DEFAULT && IterablePrototype[DEFAULT];
- var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
- var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
- var CurrentIteratorPrototype, methods, KEY;
- // fix native
- if (anyNativeIterator) {
- CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));
- if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
- if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {
- if (setPrototypeOf) {
- setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);
- } else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') {
- createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis);
- }
- }
- // Set @@toStringTag to native iterators
- setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);
- if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis;
- }
- }
- // fix Array#{values, @@iterator}.name in V8 / FF
- if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
- INCORRECT_VALUES_NAME = true;
- defaultIterator = function values() { return nativeIterator.call(this); };
- }
- // define iterator
- if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) {
- createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator);
- }
- Iterators[NAME] = defaultIterator;
- // export additional methods
- if (DEFAULT) {
- methods = {
- values: getIterationMethod(VALUES),
- keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
- entries: getIterationMethod(ENTRIES)
- };
- if (FORCED) for (KEY in methods) {
- if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
- redefine(IterablePrototype, KEY, methods[KEY]);
- }
- } else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
- }
- return methods;
- };
- },{"../internals/create-iterator-constructor":75,"../internals/create-non-enumerable-property":76,"../internals/export":85,"../internals/is-pure":106,"../internals/iterators":110,"../internals/iterators-core":109,"../internals/object-get-prototype-of":125,"../internals/object-set-prototype-of":129,"../internals/redefine":138,"../internals/set-to-string-tag":145,"../internals/well-known-symbol":169}],80:[function(require,module,exports){
- var path = require('../internals/path');
- var has = require('../internals/has');
- var wrappedWellKnownSymbolModule = require('../internals/wrapped-well-known-symbol');
- var defineProperty = require('../internals/object-define-property').f;
- module.exports = function (NAME) {
- var Symbol = path.Symbol || (path.Symbol = {});
- if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, {
- value: wrappedWellKnownSymbolModule.f(NAME)
- });
- };
- },{"../internals/has":93,"../internals/object-define-property":120,"../internals/path":134,"../internals/wrapped-well-known-symbol":171}],81:[function(require,module,exports){
- var fails = require('../internals/fails');
- // Thank's IE8 for his funny defineProperty
- module.exports = !fails(function () {
- return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
- });
- },{"../internals/fails":86}],82:[function(require,module,exports){
- var global = require('../internals/global');
- var isObject = require('../internals/is-object');
- var document = global.document;
- // typeof document.createElement is 'object' in old IE
- var EXISTS = isObject(document) && isObject(document.createElement);
- module.exports = function (it) {
- return EXISTS ? document.createElement(it) : {};
- };
- },{"../internals/global":92,"../internals/is-object":105}],83:[function(require,module,exports){
- // iterable DOM collections
- // flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
- module.exports = {
- CSSRuleList: 0,
- CSSStyleDeclaration: 0,
- CSSValueList: 0,
- ClientRectList: 0,
- DOMRectList: 0,
- DOMStringList: 0,
- DOMTokenList: 1,
- DataTransferItemList: 0,
- FileList: 0,
- HTMLAllCollection: 0,
- HTMLCollection: 0,
- HTMLFormElement: 0,
- HTMLSelectElement: 0,
- MediaList: 0,
- MimeTypeArray: 0,
- NamedNodeMap: 0,
- NodeList: 1,
- PaintRequestList: 0,
- Plugin: 0,
- PluginArray: 0,
- SVGLengthList: 0,
- SVGNumberList: 0,
- SVGPathSegList: 0,
- SVGPointList: 0,
- SVGStringList: 0,
- SVGTransformList: 0,
- SourceBufferList: 0,
- StyleSheetList: 0,
- TextTrackCueList: 0,
- TextTrackList: 0,
- TouchList: 0
- };
- },{}],84:[function(require,module,exports){
- // IE8- don't enum bug keys
- module.exports = [
- 'constructor',
- 'hasOwnProperty',
- 'isPrototypeOf',
- 'propertyIsEnumerable',
- 'toLocaleString',
- 'toString',
- 'valueOf'
- ];
- },{}],85:[function(require,module,exports){
- var global = require('../internals/global');
- var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var redefine = require('../internals/redefine');
- var setGlobal = require('../internals/set-global');
- var copyConstructorProperties = require('../internals/copy-constructor-properties');
- var isForced = require('../internals/is-forced');
- /*
- options.target - name of the target object
- options.global - target is the global object
- options.stat - export as static methods of target
- options.proto - export as prototype methods of target
- options.real - real prototype method for the `pure` version
- options.forced - export even if the native feature is available
- options.bind - bind methods to the target, required for the `pure` version
- options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
- options.unsafe - use the simple assignment of property instead of delete + defineProperty
- options.sham - add a flag to not completely full polyfills
- options.enumerable - export as enumerable property
- options.noTargetGet - prevent calling a getter on target
- */
- module.exports = function (options, source) {
- var TARGET = options.target;
- var GLOBAL = options.global;
- var STATIC = options.stat;
- var FORCED, target, key, targetProperty, sourceProperty, descriptor;
- if (GLOBAL) {
- target = global;
- } else if (STATIC) {
- target = global[TARGET] || setGlobal(TARGET, {});
- } else {
- target = (global[TARGET] || {}).prototype;
- }
- if (target) for (key in source) {
- sourceProperty = source[key];
- if (options.noTargetGet) {
- descriptor = getOwnPropertyDescriptor(target, key);
- targetProperty = descriptor && descriptor.value;
- } else targetProperty = target[key];
- FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
- // contained in target
- if (!FORCED && targetProperty !== undefined) {
- if (typeof sourceProperty === typeof targetProperty) continue;
- copyConstructorProperties(sourceProperty, targetProperty);
- }
- // add a flag to not completely full polyfills
- if (options.sham || (targetProperty && targetProperty.sham)) {
- createNonEnumerableProperty(sourceProperty, 'sham', true);
- }
- // extend global
- redefine(target, key, sourceProperty, options);
- }
- };
- },{"../internals/copy-constructor-properties":72,"../internals/create-non-enumerable-property":76,"../internals/global":92,"../internals/is-forced":103,"../internals/object-get-own-property-descriptor":121,"../internals/redefine":138,"../internals/set-global":143}],86:[function(require,module,exports){
- module.exports = function (exec) {
- try {
- return !!exec();
- } catch (error) {
- return true;
- }
- };
- },{}],87:[function(require,module,exports){
- 'use strict';
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var redefine = require('../internals/redefine');
- var fails = require('../internals/fails');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var regexpExec = require('../internals/regexp-exec');
- var SPECIES = wellKnownSymbol('species');
- var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
- // #replace needs built-in support for named groups.
- // #match works fine because it just return the exec results, even if it has
- // a "grops" property.
- var re = /./;
- re.exec = function () {
- var result = [];
- result.groups = { a: '7' };
- return result;
- };
- return ''.replace(re, '$<a>') !== '7';
- });
- // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
- // Weex JS has frozen built-in prototypes, so use try / catch wrapper
- var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () {
- var re = /(?:)/;
- var originalExec = re.exec;
- re.exec = function () { return originalExec.apply(this, arguments); };
- var result = 'ab'.split(re);
- return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b';
- });
- module.exports = function (KEY, length, exec, sham) {
- var SYMBOL = wellKnownSymbol(KEY);
- var DELEGATES_TO_SYMBOL = !fails(function () {
- // String methods call symbol-named RegEp methods
- var O = {};
- O[SYMBOL] = function () { return 7; };
- return ''[KEY](O) != 7;
- });
- var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () {
- // Symbol-named RegExp methods call .exec
- var execCalled = false;
- var re = /a/;
- if (KEY === 'split') {
- // We can't use real regex here since it causes deoptimization
- // and serious performance degradation in V8
- // https://github.com/zloirock/core-js/issues/306
- re = {};
- // RegExp[@@split] doesn't call the regex's exec method, but first creates
- // a new one. We need to return the patched regex when creating the new one.
- re.constructor = {};
- re.constructor[SPECIES] = function () { return re; };
- re.flags = '';
- re[SYMBOL] = /./[SYMBOL];
- }
- re.exec = function () { execCalled = true; return null; };
- re[SYMBOL]('');
- return !execCalled;
- });
- if (
- !DELEGATES_TO_SYMBOL ||
- !DELEGATES_TO_EXEC ||
- (KEY === 'replace' && !REPLACE_SUPPORTS_NAMED_GROUPS) ||
- (KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC)
- ) {
- var nativeRegExpMethod = /./[SYMBOL];
- var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {
- if (regexp.exec === regexpExec) {
- if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
- // The native String method already delegates to @@method (this
- // polyfilled function), leasing to infinite recursion.
- // We avoid it by directly calling the native @@method method.
- return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) };
- }
- return { done: true, value: nativeMethod.call(str, regexp, arg2) };
- }
- return { done: false };
- });
- var stringMethod = methods[0];
- var regexMethod = methods[1];
- redefine(String.prototype, KEY, stringMethod);
- redefine(RegExp.prototype, SYMBOL, length == 2
- // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
- // 21.2.5.11 RegExp.prototype[@@split](string, limit)
- ? function (string, arg) { return regexMethod.call(string, this, arg); }
- // 21.2.5.6 RegExp.prototype[@@match](string)
- // 21.2.5.9 RegExp.prototype[@@search](string)
- : function (string) { return regexMethod.call(string, this); }
- );
- if (sham) createNonEnumerableProperty(RegExp.prototype[SYMBOL], 'sham', true);
- }
- };
- },{"../internals/create-non-enumerable-property":76,"../internals/fails":86,"../internals/redefine":138,"../internals/regexp-exec":140,"../internals/well-known-symbol":169}],88:[function(require,module,exports){
- 'use strict';
- var aFunction = require('../internals/a-function');
- var isObject = require('../internals/is-object');
- var slice = [].slice;
- var factories = {};
- var construct = function (C, argsLength, args) {
- if (!(argsLength in factories)) {
- for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']';
- // eslint-disable-next-line no-new-func
- factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')');
- } return factories[argsLength](C, args);
- };
- // `Function.prototype.bind` method implementation
- // https://tc39.github.io/ecma262/#sec-function.prototype.bind
- module.exports = Function.bind || function bind(that /* , ...args */) {
- var fn = aFunction(this);
- var partArgs = slice.call(arguments, 1);
- var boundFunction = function bound(/* args... */) {
- var args = partArgs.concat(slice.call(arguments));
- return this instanceof boundFunction ? construct(fn, args.length, args) : fn.apply(that, args);
- };
- if (isObject(fn.prototype)) boundFunction.prototype = fn.prototype;
- return boundFunction;
- };
- },{"../internals/a-function":50,"../internals/is-object":105}],89:[function(require,module,exports){
- var shared = require('../internals/shared');
- module.exports = shared('native-function-to-string', Function.toString);
- },{"../internals/shared":148}],90:[function(require,module,exports){
- var path = require('../internals/path');
- var global = require('../internals/global');
- var aFunction = function (variable) {
- return typeof variable == 'function' ? variable : undefined;
- };
- module.exports = function (namespace, method) {
- return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])
- : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];
- };
- },{"../internals/global":92,"../internals/path":134}],91:[function(require,module,exports){
- var classof = require('../internals/classof');
- var Iterators = require('../internals/iterators');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var ITERATOR = wellKnownSymbol('iterator');
- module.exports = function (it) {
- if (it != undefined) return it[ITERATOR]
- || it['@@iterator']
- || Iterators[classof(it)];
- };
- },{"../internals/classof":71,"../internals/iterators":110,"../internals/well-known-symbol":169}],92:[function(require,module,exports){
- (function (global){
- var check = function (it) {
- return it && it.Math == Math && it;
- };
- // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
- module.exports =
- // eslint-disable-next-line no-undef
- check(typeof globalThis == 'object' && globalThis) ||
- check(typeof window == 'object' && window) ||
- check(typeof self == 'object' && self) ||
- check(typeof global == 'object' && global) ||
- // eslint-disable-next-line no-new-func
- Function('return this')();
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],93:[function(require,module,exports){
- var hasOwnProperty = {}.hasOwnProperty;
- module.exports = function (it, key) {
- return hasOwnProperty.call(it, key);
- };
- },{}],94:[function(require,module,exports){
- module.exports = {};
- },{}],95:[function(require,module,exports){
- var global = require('../internals/global');
- module.exports = function (a, b) {
- var console = global.console;
- if (console && console.error) {
- arguments.length === 1 ? console.error(a) : console.error(a, b);
- }
- };
- },{"../internals/global":92}],96:[function(require,module,exports){
- var getBuiltIn = require('../internals/get-built-in');
- module.exports = getBuiltIn('document', 'documentElement');
- },{"../internals/get-built-in":90}],97:[function(require,module,exports){
- var DESCRIPTORS = require('../internals/descriptors');
- var fails = require('../internals/fails');
- var createElement = require('../internals/document-create-element');
- // Thank's IE8 for his funny defineProperty
- module.exports = !DESCRIPTORS && !fails(function () {
- return Object.defineProperty(createElement('div'), 'a', {
- get: function () { return 7; }
- }).a != 7;
- });
- },{"../internals/descriptors":81,"../internals/document-create-element":82,"../internals/fails":86}],98:[function(require,module,exports){
- var fails = require('../internals/fails');
- var classof = require('../internals/classof-raw');
- var split = ''.split;
- // fallback for non-array-like ES3 and non-enumerable old V8 strings
- module.exports = fails(function () {
- // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
- // eslint-disable-next-line no-prototype-builtins
- return !Object('z').propertyIsEnumerable(0);
- }) ? function (it) {
- return classof(it) == 'String' ? split.call(it, '') : Object(it);
- } : Object;
- },{"../internals/classof-raw":70,"../internals/fails":86}],99:[function(require,module,exports){
- var isObject = require('../internals/is-object');
- var setPrototypeOf = require('../internals/object-set-prototype-of');
- // makes subclassing work correct for wrapped built-ins
- module.exports = function ($this, dummy, Wrapper) {
- var NewTarget, NewTargetPrototype;
- if (
- // it can work only with native `setPrototypeOf`
- setPrototypeOf &&
- // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
- typeof (NewTarget = dummy.constructor) == 'function' &&
- NewTarget !== Wrapper &&
- isObject(NewTargetPrototype = NewTarget.prototype) &&
- NewTargetPrototype !== Wrapper.prototype
- ) setPrototypeOf($this, NewTargetPrototype);
- return $this;
- };
- },{"../internals/is-object":105,"../internals/object-set-prototype-of":129}],100:[function(require,module,exports){
- var NATIVE_WEAK_MAP = require('../internals/native-weak-map');
- var global = require('../internals/global');
- var isObject = require('../internals/is-object');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var objectHas = require('../internals/has');
- var sharedKey = require('../internals/shared-key');
- var hiddenKeys = require('../internals/hidden-keys');
- var WeakMap = global.WeakMap;
- var set, get, has;
- var enforce = function (it) {
- return has(it) ? get(it) : set(it, {});
- };
- var getterFor = function (TYPE) {
- return function (it) {
- var state;
- if (!isObject(it) || (state = get(it)).type !== TYPE) {
- throw TypeError('Incompatible receiver, ' + TYPE + ' required');
- } return state;
- };
- };
- if (NATIVE_WEAK_MAP) {
- var store = new WeakMap();
- var wmget = store.get;
- var wmhas = store.has;
- var wmset = store.set;
- set = function (it, metadata) {
- wmset.call(store, it, metadata);
- return metadata;
- };
- get = function (it) {
- return wmget.call(store, it) || {};
- };
- has = function (it) {
- return wmhas.call(store, it);
- };
- } else {
- var STATE = sharedKey('state');
- hiddenKeys[STATE] = true;
- set = function (it, metadata) {
- createNonEnumerableProperty(it, STATE, metadata);
- return metadata;
- };
- get = function (it) {
- return objectHas(it, STATE) ? it[STATE] : {};
- };
- has = function (it) {
- return objectHas(it, STATE);
- };
- }
- module.exports = {
- set: set,
- get: get,
- has: has,
- enforce: enforce,
- getterFor: getterFor
- };
- },{"../internals/create-non-enumerable-property":76,"../internals/global":92,"../internals/has":93,"../internals/hidden-keys":94,"../internals/is-object":105,"../internals/native-weak-map":114,"../internals/shared-key":146}],101:[function(require,module,exports){
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var Iterators = require('../internals/iterators');
- var ITERATOR = wellKnownSymbol('iterator');
- var ArrayPrototype = Array.prototype;
- // check on default Array iterator
- module.exports = function (it) {
- return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
- };
- },{"../internals/iterators":110,"../internals/well-known-symbol":169}],102:[function(require,module,exports){
- var classof = require('../internals/classof-raw');
- // `IsArray` abstract operation
- // https://tc39.github.io/ecma262/#sec-isarray
- module.exports = Array.isArray || function isArray(arg) {
- return classof(arg) == 'Array';
- };
- },{"../internals/classof-raw":70}],103:[function(require,module,exports){
- var fails = require('../internals/fails');
- var replacement = /#|\.prototype\./;
- var isForced = function (feature, detection) {
- var value = data[normalize(feature)];
- return value == POLYFILL ? true
- : value == NATIVE ? false
- : typeof detection == 'function' ? fails(detection)
- : !!detection;
- };
- var normalize = isForced.normalize = function (string) {
- return String(string).replace(replacement, '.').toLowerCase();
- };
- var data = isForced.data = {};
- var NATIVE = isForced.NATIVE = 'N';
- var POLYFILL = isForced.POLYFILL = 'P';
- module.exports = isForced;
- },{"../internals/fails":86}],104:[function(require,module,exports){
- var userAgent = require('../internals/user-agent');
- module.exports = /(iphone|ipod|ipad).*applewebkit/i.test(userAgent);
- },{"../internals/user-agent":167}],105:[function(require,module,exports){
- module.exports = function (it) {
- return typeof it === 'object' ? it !== null : typeof it === 'function';
- };
- },{}],106:[function(require,module,exports){
- module.exports = false;
- },{}],107:[function(require,module,exports){
- var isObject = require('../internals/is-object');
- var classof = require('../internals/classof-raw');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var MATCH = wellKnownSymbol('match');
- // `IsRegExp` abstract operation
- // https://tc39.github.io/ecma262/#sec-isregexp
- module.exports = function (it) {
- var isRegExp;
- return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) == 'RegExp');
- };
- },{"../internals/classof-raw":70,"../internals/is-object":105,"../internals/well-known-symbol":169}],108:[function(require,module,exports){
- var anObject = require('../internals/an-object');
- var isArrayIteratorMethod = require('../internals/is-array-iterator-method');
- var toLength = require('../internals/to-length');
- var bind = require('../internals/bind-context');
- var getIteratorMethod = require('../internals/get-iterator-method');
- var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');
- var Result = function (stopped, result) {
- this.stopped = stopped;
- this.result = result;
- };
- var iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) {
- var boundFunction = bind(fn, that, AS_ENTRIES ? 2 : 1);
- var iterator, iterFn, index, length, result, next, step;
- if (IS_ITERATOR) {
- iterator = iterable;
- } else {
- iterFn = getIteratorMethod(iterable);
- if (typeof iterFn != 'function') throw TypeError('Target is not iterable');
- // optimisation for array iterators
- if (isArrayIteratorMethod(iterFn)) {
- for (index = 0, length = toLength(iterable.length); length > index; index++) {
- result = AS_ENTRIES
- ? boundFunction(anObject(step = iterable[index])[0], step[1])
- : boundFunction(iterable[index]);
- if (result && result instanceof Result) return result;
- } return new Result(false);
- }
- iterator = iterFn.call(iterable);
- }
- next = iterator.next;
- while (!(step = next.call(iterator)).done) {
- result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES);
- if (typeof result == 'object' && result && result instanceof Result) return result;
- } return new Result(false);
- };
- iterate.stop = function (result) {
- return new Result(true, result);
- };
- },{"../internals/an-object":55,"../internals/bind-context":67,"../internals/call-with-safe-iteration-closing":68,"../internals/get-iterator-method":91,"../internals/is-array-iterator-method":101,"../internals/to-length":158}],109:[function(require,module,exports){
- 'use strict';
- var getPrototypeOf = require('../internals/object-get-prototype-of');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var has = require('../internals/has');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var IS_PURE = require('../internals/is-pure');
- var ITERATOR = wellKnownSymbol('iterator');
- var BUGGY_SAFARI_ITERATORS = false;
- var returnThis = function () { return this; };
- // `%IteratorPrototype%` object
- // https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object
- var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
- if ([].keys) {
- arrayIterator = [].keys();
- // Safari 8 has buggy iterators w/o `next`
- if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
- else {
- PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
- if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
- }
- }
- if (IteratorPrototype == undefined) IteratorPrototype = {};
- // 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
- if (!IS_PURE && !has(IteratorPrototype, ITERATOR)) {
- createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis);
- }
- module.exports = {
- IteratorPrototype: IteratorPrototype,
- BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
- };
- },{"../internals/create-non-enumerable-property":76,"../internals/has":93,"../internals/is-pure":106,"../internals/object-get-prototype-of":125,"../internals/well-known-symbol":169}],110:[function(require,module,exports){
- arguments[4][94][0].apply(exports,arguments)
- },{"dup":94}],111:[function(require,module,exports){
- var global = require('../internals/global');
- var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
- var classof = require('../internals/classof-raw');
- var macrotask = require('../internals/task').set;
- var IS_IOS = require('../internals/is-ios');
- var MutationObserver = global.MutationObserver || global.WebKitMutationObserver;
- var process = global.process;
- var Promise = global.Promise;
- var IS_NODE = classof(process) == 'process';
- // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
- var queueMicrotaskDescriptor = getOwnPropertyDescriptor(global, 'queueMicrotask');
- var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;
- var flush, head, last, notify, toggle, node, promise, then;
- // modern engines have queueMicrotask method
- if (!queueMicrotask) {
- flush = function () {
- var parent, fn;
- if (IS_NODE && (parent = process.domain)) parent.exit();
- while (head) {
- fn = head.fn;
- head = head.next;
- try {
- fn();
- } catch (error) {
- if (head) notify();
- else last = undefined;
- throw error;
- }
- } last = undefined;
- if (parent) parent.enter();
- };
- // Node.js
- if (IS_NODE) {
- notify = function () {
- process.nextTick(flush);
- };
- // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
- } else if (MutationObserver && !IS_IOS) {
- toggle = true;
- node = document.createTextNode('');
- new MutationObserver(flush).observe(node, { characterData: true });
- notify = function () {
- node.data = toggle = !toggle;
- };
- // environments with maybe non-completely correct, but existent Promise
- } else if (Promise && Promise.resolve) {
- // Promise.resolve without an argument throws an error in LG WebOS 2
- promise = Promise.resolve(undefined);
- then = promise.then;
- notify = function () {
- then.call(promise, flush);
- };
- // for other environments - macrotask based on:
- // - setImmediate
- // - MessageChannel
- // - window.postMessag
- // - onreadystatechange
- // - setTimeout
- } else {
- notify = function () {
- // strange IE + webpack dev server bug - use .call(global)
- macrotask.call(global, flush);
- };
- }
- }
- module.exports = queueMicrotask || function (fn) {
- var task = { fn: fn, next: undefined };
- if (last) last.next = task;
- if (!head) {
- head = task;
- notify();
- } last = task;
- };
- },{"../internals/classof-raw":70,"../internals/global":92,"../internals/is-ios":104,"../internals/object-get-own-property-descriptor":121,"../internals/task":153}],112:[function(require,module,exports){
- var global = require('../internals/global');
- module.exports = global.Promise;
- },{"../internals/global":92}],113:[function(require,module,exports){
- var fails = require('../internals/fails');
- module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
- // Chrome 38 Symbol has incorrect toString conversion
- // eslint-disable-next-line no-undef
- return !String(Symbol());
- });
- },{"../internals/fails":86}],114:[function(require,module,exports){
- var global = require('../internals/global');
- var nativeFunctionToString = require('../internals/function-to-string');
- var WeakMap = global.WeakMap;
- module.exports = typeof WeakMap === 'function' && /native code/.test(nativeFunctionToString.call(WeakMap));
- },{"../internals/function-to-string":89,"../internals/global":92}],115:[function(require,module,exports){
- 'use strict';
- var aFunction = require('../internals/a-function');
- var PromiseCapability = function (C) {
- var resolve, reject;
- this.promise = new C(function ($$resolve, $$reject) {
- if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
- resolve = $$resolve;
- reject = $$reject;
- });
- this.resolve = aFunction(resolve);
- this.reject = aFunction(reject);
- };
- // 25.4.1.5 NewPromiseCapability(C)
- module.exports.f = function (C) {
- return new PromiseCapability(C);
- };
- },{"../internals/a-function":50}],116:[function(require,module,exports){
- var isRegExp = require('../internals/is-regexp');
- module.exports = function (it) {
- if (isRegExp(it)) {
- throw TypeError("The method doesn't accept regular expressions");
- } return it;
- };
- },{"../internals/is-regexp":107}],117:[function(require,module,exports){
- 'use strict';
- var DESCRIPTORS = require('../internals/descriptors');
- var fails = require('../internals/fails');
- var objectKeys = require('../internals/object-keys');
- var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');
- var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');
- var toObject = require('../internals/to-object');
- var IndexedObject = require('../internals/indexed-object');
- var nativeAssign = Object.assign;
- // `Object.assign` method
- // https://tc39.github.io/ecma262/#sec-object.assign
- // should work with symbols and should have deterministic property order (V8 bug)
- module.exports = !nativeAssign || fails(function () {
- var A = {};
- var B = {};
- // eslint-disable-next-line no-undef
- var symbol = Symbol();
- var alphabet = 'abcdefghijklmnopqrst';
- A[symbol] = 7;
- alphabet.split('').forEach(function (chr) { B[chr] = chr; });
- return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
- }) ? function assign(target, source) { // eslint-disable-line no-unused-vars
- var T = toObject(target);
- var argumentsLength = arguments.length;
- var index = 1;
- var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
- var propertyIsEnumerable = propertyIsEnumerableModule.f;
- while (argumentsLength > index) {
- var S = IndexedObject(arguments[index++]);
- var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
- var length = keys.length;
- var j = 0;
- var key;
- while (length > j) {
- key = keys[j++];
- if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key];
- }
- } return T;
- } : nativeAssign;
- },{"../internals/descriptors":81,"../internals/fails":86,"../internals/indexed-object":98,"../internals/object-get-own-property-symbols":124,"../internals/object-keys":127,"../internals/object-property-is-enumerable":128,"../internals/to-object":159}],118:[function(require,module,exports){
- var anObject = require('../internals/an-object');
- var defineProperties = require('../internals/object-define-properties');
- var enumBugKeys = require('../internals/enum-bug-keys');
- var hiddenKeys = require('../internals/hidden-keys');
- var html = require('../internals/html');
- var documentCreateElement = require('../internals/document-create-element');
- var sharedKey = require('../internals/shared-key');
- var IE_PROTO = sharedKey('IE_PROTO');
- var PROTOTYPE = 'prototype';
- var Empty = function () { /* empty */ };
- // Create object with fake `null` prototype: use iframe Object with cleared prototype
- var createDict = function () {
- // Thrash, waste and sodomy: IE GC bug
- var iframe = documentCreateElement('iframe');
- var length = enumBugKeys.length;
- var lt = '<';
- var script = 'script';
- var gt = '>';
- var js = 'java' + script + ':';
- var iframeDocument;
- iframe.style.display = 'none';
- html.appendChild(iframe);
- iframe.src = String(js);
- iframeDocument = iframe.contentWindow.document;
- iframeDocument.open();
- iframeDocument.write(lt + script + gt + 'document.F=Object' + lt + '/' + script + gt);
- iframeDocument.close();
- createDict = iframeDocument.F;
- while (length--) delete createDict[PROTOTYPE][enumBugKeys[length]];
- return createDict();
- };
- // `Object.create` method
- // https://tc39.github.io/ecma262/#sec-object.create
- module.exports = Object.create || function create(O, Properties) {
- var result;
- if (O !== null) {
- Empty[PROTOTYPE] = anObject(O);
- result = new Empty();
- Empty[PROTOTYPE] = null;
- // add "__proto__" for Object.getPrototypeOf polyfill
- result[IE_PROTO] = O;
- } else result = createDict();
- return Properties === undefined ? result : defineProperties(result, Properties);
- };
- hiddenKeys[IE_PROTO] = true;
- },{"../internals/an-object":55,"../internals/document-create-element":82,"../internals/enum-bug-keys":84,"../internals/hidden-keys":94,"../internals/html":96,"../internals/object-define-properties":119,"../internals/shared-key":146}],119:[function(require,module,exports){
- var DESCRIPTORS = require('../internals/descriptors');
- var definePropertyModule = require('../internals/object-define-property');
- var anObject = require('../internals/an-object');
- var objectKeys = require('../internals/object-keys');
- // `Object.defineProperties` method
- // https://tc39.github.io/ecma262/#sec-object.defineproperties
- module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) {
- anObject(O);
- var keys = objectKeys(Properties);
- var length = keys.length;
- var index = 0;
- var key;
- while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]);
- return O;
- };
- },{"../internals/an-object":55,"../internals/descriptors":81,"../internals/object-define-property":120,"../internals/object-keys":127}],120:[function(require,module,exports){
- var DESCRIPTORS = require('../internals/descriptors');
- var IE8_DOM_DEFINE = require('../internals/ie8-dom-define');
- var anObject = require('../internals/an-object');
- var toPrimitive = require('../internals/to-primitive');
- var nativeDefineProperty = Object.defineProperty;
- // `Object.defineProperty` method
- // https://tc39.github.io/ecma262/#sec-object.defineproperty
- exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
- anObject(O);
- P = toPrimitive(P, true);
- anObject(Attributes);
- if (IE8_DOM_DEFINE) try {
- return nativeDefineProperty(O, P, Attributes);
- } catch (error) { /* empty */ }
- if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
- if ('value' in Attributes) O[P] = Attributes.value;
- return O;
- };
- },{"../internals/an-object":55,"../internals/descriptors":81,"../internals/ie8-dom-define":97,"../internals/to-primitive":162}],121:[function(require,module,exports){
- var DESCRIPTORS = require('../internals/descriptors');
- var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');
- var createPropertyDescriptor = require('../internals/create-property-descriptor');
- var toIndexedObject = require('../internals/to-indexed-object');
- var toPrimitive = require('../internals/to-primitive');
- var has = require('../internals/has');
- var IE8_DOM_DEFINE = require('../internals/ie8-dom-define');
- var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
- // `Object.getOwnPropertyDescriptor` method
- // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
- exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
- O = toIndexedObject(O);
- P = toPrimitive(P, true);
- if (IE8_DOM_DEFINE) try {
- return nativeGetOwnPropertyDescriptor(O, P);
- } catch (error) { /* empty */ }
- if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);
- };
- },{"../internals/create-property-descriptor":77,"../internals/descriptors":81,"../internals/has":93,"../internals/ie8-dom-define":97,"../internals/object-property-is-enumerable":128,"../internals/to-indexed-object":156,"../internals/to-primitive":162}],122:[function(require,module,exports){
- var toIndexedObject = require('../internals/to-indexed-object');
- var nativeGetOwnPropertyNames = require('../internals/object-get-own-property-names').f;
- var toString = {}.toString;
- var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
- ? Object.getOwnPropertyNames(window) : [];
- var getWindowNames = function (it) {
- try {
- return nativeGetOwnPropertyNames(it);
- } catch (error) {
- return windowNames.slice();
- }
- };
- // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
- module.exports.f = function getOwnPropertyNames(it) {
- return windowNames && toString.call(it) == '[object Window]'
- ? getWindowNames(it)
- : nativeGetOwnPropertyNames(toIndexedObject(it));
- };
- },{"../internals/object-get-own-property-names":123,"../internals/to-indexed-object":156}],123:[function(require,module,exports){
- var internalObjectKeys = require('../internals/object-keys-internal');
- var enumBugKeys = require('../internals/enum-bug-keys');
- var hiddenKeys = enumBugKeys.concat('length', 'prototype');
- // `Object.getOwnPropertyNames` method
- // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
- exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
- return internalObjectKeys(O, hiddenKeys);
- };
- },{"../internals/enum-bug-keys":84,"../internals/object-keys-internal":126}],124:[function(require,module,exports){
- exports.f = Object.getOwnPropertySymbols;
- },{}],125:[function(require,module,exports){
- var has = require('../internals/has');
- var toObject = require('../internals/to-object');
- var sharedKey = require('../internals/shared-key');
- var CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter');
- var IE_PROTO = sharedKey('IE_PROTO');
- var ObjectPrototype = Object.prototype;
- // `Object.getPrototypeOf` method
- // https://tc39.github.io/ecma262/#sec-object.getprototypeof
- module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) {
- O = toObject(O);
- if (has(O, IE_PROTO)) return O[IE_PROTO];
- if (typeof O.constructor == 'function' && O instanceof O.constructor) {
- return O.constructor.prototype;
- } return O instanceof Object ? ObjectPrototype : null;
- };
- },{"../internals/correct-prototype-getter":74,"../internals/has":93,"../internals/shared-key":146,"../internals/to-object":159}],126:[function(require,module,exports){
- var has = require('../internals/has');
- var toIndexedObject = require('../internals/to-indexed-object');
- var indexOf = require('../internals/array-includes').indexOf;
- var hiddenKeys = require('../internals/hidden-keys');
- module.exports = function (object, names) {
- var O = toIndexedObject(object);
- var i = 0;
- var result = [];
- var key;
- for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
- // Don't enum bug & hidden keys
- while (names.length > i) if (has(O, key = names[i++])) {
- ~indexOf(result, key) || result.push(key);
- }
- return result;
- };
- },{"../internals/array-includes":61,"../internals/has":93,"../internals/hidden-keys":94,"../internals/to-indexed-object":156}],127:[function(require,module,exports){
- var internalObjectKeys = require('../internals/object-keys-internal');
- var enumBugKeys = require('../internals/enum-bug-keys');
- // `Object.keys` method
- // https://tc39.github.io/ecma262/#sec-object.keys
- module.exports = Object.keys || function keys(O) {
- return internalObjectKeys(O, enumBugKeys);
- };
- },{"../internals/enum-bug-keys":84,"../internals/object-keys-internal":126}],128:[function(require,module,exports){
- 'use strict';
- var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
- var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
- // Nashorn ~ JDK8 bug
- var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
- // `Object.prototype.propertyIsEnumerable` method implementation
- // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
- exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
- var descriptor = getOwnPropertyDescriptor(this, V);
- return !!descriptor && descriptor.enumerable;
- } : nativePropertyIsEnumerable;
- },{}],129:[function(require,module,exports){
- var anObject = require('../internals/an-object');
- var aPossiblePrototype = require('../internals/a-possible-prototype');
- // `Object.setPrototypeOf` method
- // https://tc39.github.io/ecma262/#sec-object.setprototypeof
- // Works with __proto__ only. Old v8 can't work with null proto objects.
- /* eslint-disable no-proto */
- module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
- var CORRECT_SETTER = false;
- var test = {};
- var setter;
- try {
- setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
- setter.call(test, []);
- CORRECT_SETTER = test instanceof Array;
- } catch (error) { /* empty */ }
- return function setPrototypeOf(O, proto) {
- anObject(O);
- aPossiblePrototype(proto);
- if (CORRECT_SETTER) setter.call(O, proto);
- else O.__proto__ = proto;
- return O;
- };
- }() : undefined);
- },{"../internals/a-possible-prototype":51,"../internals/an-object":55}],130:[function(require,module,exports){
- var DESCRIPTORS = require('../internals/descriptors');
- var objectKeys = require('../internals/object-keys');
- var toIndexedObject = require('../internals/to-indexed-object');
- var propertyIsEnumerable = require('../internals/object-property-is-enumerable').f;
- // `Object.{ entries, values }` methods implementation
- var createMethod = function (TO_ENTRIES) {
- return function (it) {
- var O = toIndexedObject(it);
- var keys = objectKeys(O);
- var length = keys.length;
- var i = 0;
- var result = [];
- var key;
- while (length > i) {
- key = keys[i++];
- if (!DESCRIPTORS || propertyIsEnumerable.call(O, key)) {
- result.push(TO_ENTRIES ? [key, O[key]] : O[key]);
- }
- }
- return result;
- };
- };
- module.exports = {
- // `Object.entries` method
- // https://tc39.github.io/ecma262/#sec-object.entries
- entries: createMethod(true),
- // `Object.values` method
- // https://tc39.github.io/ecma262/#sec-object.values
- values: createMethod(false)
- };
- },{"../internals/descriptors":81,"../internals/object-keys":127,"../internals/object-property-is-enumerable":128,"../internals/to-indexed-object":156}],131:[function(require,module,exports){
- 'use strict';
- var classof = require('../internals/classof');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var TO_STRING_TAG = wellKnownSymbol('toStringTag');
- var test = {};
- test[TO_STRING_TAG] = 'z';
- // `Object.prototype.toString` method implementation
- // https://tc39.github.io/ecma262/#sec-object.prototype.tostring
- module.exports = String(test) !== '[object z]' ? function toString() {
- return '[object ' + classof(this) + ']';
- } : test.toString;
- },{"../internals/classof":71,"../internals/well-known-symbol":169}],132:[function(require,module,exports){
- var getBuiltIn = require('../internals/get-built-in');
- var getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');
- var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');
- var anObject = require('../internals/an-object');
- // all object keys, includes non-enumerable and symbols
- module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
- var keys = getOwnPropertyNamesModule.f(anObject(it));
- var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
- return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
- };
- },{"../internals/an-object":55,"../internals/get-built-in":90,"../internals/object-get-own-property-names":123,"../internals/object-get-own-property-symbols":124}],133:[function(require,module,exports){
- var global = require('../internals/global');
- var trim = require('../internals/string-trim').trim;
- var whitespaces = require('../internals/whitespaces');
- var nativeParseInt = global.parseInt;
- var hex = /^[+-]?0[Xx]/;
- var FORCED = nativeParseInt(whitespaces + '08') !== 8 || nativeParseInt(whitespaces + '0x16') !== 22;
- // `parseInt` method
- // https://tc39.github.io/ecma262/#sec-parseint-string-radix
- module.exports = FORCED ? function parseInt(string, radix) {
- var S = trim(String(string));
- return nativeParseInt(S, (radix >>> 0) || (hex.test(S) ? 16 : 10));
- } : nativeParseInt;
- },{"../internals/global":92,"../internals/string-trim":152,"../internals/whitespaces":170}],134:[function(require,module,exports){
- module.exports = require('../internals/global');
- },{"../internals/global":92}],135:[function(require,module,exports){
- module.exports = function (exec) {
- try {
- return { error: false, value: exec() };
- } catch (error) {
- return { error: true, value: error };
- }
- };
- },{}],136:[function(require,module,exports){
- var anObject = require('../internals/an-object');
- var isObject = require('../internals/is-object');
- var newPromiseCapability = require('../internals/new-promise-capability');
- module.exports = function (C, x) {
- anObject(C);
- if (isObject(x) && x.constructor === C) return x;
- var promiseCapability = newPromiseCapability.f(C);
- var resolve = promiseCapability.resolve;
- resolve(x);
- return promiseCapability.promise;
- };
- },{"../internals/an-object":55,"../internals/is-object":105,"../internals/new-promise-capability":115}],137:[function(require,module,exports){
- var redefine = require('../internals/redefine');
- module.exports = function (target, src, options) {
- for (var key in src) redefine(target, key, src[key], options);
- return target;
- };
- },{"../internals/redefine":138}],138:[function(require,module,exports){
- var global = require('../internals/global');
- var shared = require('../internals/shared');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var has = require('../internals/has');
- var setGlobal = require('../internals/set-global');
- var nativeFunctionToString = require('../internals/function-to-string');
- var InternalStateModule = require('../internals/internal-state');
- var getInternalState = InternalStateModule.get;
- var enforceInternalState = InternalStateModule.enforce;
- var TEMPLATE = String(nativeFunctionToString).split('toString');
- shared('inspectSource', function (it) {
- return nativeFunctionToString.call(it);
- });
- (module.exports = function (O, key, value, options) {
- var unsafe = options ? !!options.unsafe : false;
- var simple = options ? !!options.enumerable : false;
- var noTargetGet = options ? !!options.noTargetGet : false;
- if (typeof value == 'function') {
- if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);
- enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
- }
- if (O === global) {
- if (simple) O[key] = value;
- else setGlobal(key, value);
- return;
- } else if (!unsafe) {
- delete O[key];
- } else if (!noTargetGet && O[key]) {
- simple = true;
- }
- if (simple) O[key] = value;
- else createNonEnumerableProperty(O, key, value);
- // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
- })(Function.prototype, 'toString', function toString() {
- return typeof this == 'function' && getInternalState(this).source || nativeFunctionToString.call(this);
- });
- },{"../internals/create-non-enumerable-property":76,"../internals/function-to-string":89,"../internals/global":92,"../internals/has":93,"../internals/internal-state":100,"../internals/set-global":143,"../internals/shared":148}],139:[function(require,module,exports){
- var classof = require('./classof-raw');
- var regexpExec = require('./regexp-exec');
- // `RegExpExec` abstract operation
- // https://tc39.github.io/ecma262/#sec-regexpexec
- module.exports = function (R, S) {
- var exec = R.exec;
- if (typeof exec === 'function') {
- var result = exec.call(R, S);
- if (typeof result !== 'object') {
- throw TypeError('RegExp exec method returned something other than an Object or null');
- }
- return result;
- }
- if (classof(R) !== 'RegExp') {
- throw TypeError('RegExp#exec called on incompatible receiver');
- }
- return regexpExec.call(R, S);
- };
- },{"./classof-raw":70,"./regexp-exec":140}],140:[function(require,module,exports){
- 'use strict';
- var regexpFlags = require('./regexp-flags');
- var nativeExec = RegExp.prototype.exec;
- // This always refers to the native implementation, because the
- // String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,
- // which loads this file before patching the method.
- var nativeReplace = String.prototype.replace;
- var patchedExec = nativeExec;
- var UPDATES_LAST_INDEX_WRONG = (function () {
- var re1 = /a/;
- var re2 = /b*/g;
- nativeExec.call(re1, 'a');
- nativeExec.call(re2, 'a');
- return re1.lastIndex !== 0 || re2.lastIndex !== 0;
- })();
- // nonparticipating capturing group, copied from es5-shim's String#split patch.
- var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
- var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED;
- if (PATCH) {
- patchedExec = function exec(str) {
- var re = this;
- var lastIndex, reCopy, match, i;
- if (NPCG_INCLUDED) {
- reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re));
- }
- if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;
- match = nativeExec.call(re, str);
- if (UPDATES_LAST_INDEX_WRONG && match) {
- re.lastIndex = re.global ? match.index + match[0].length : lastIndex;
- }
- if (NPCG_INCLUDED && match && match.length > 1) {
- // Fix browsers whose `exec` methods don't consistently return `undefined`
- // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
- nativeReplace.call(match[0], reCopy, function () {
- for (i = 1; i < arguments.length - 2; i++) {
- if (arguments[i] === undefined) match[i] = undefined;
- }
- });
- }
- return match;
- };
- }
- module.exports = patchedExec;
- },{"./regexp-flags":141}],141:[function(require,module,exports){
- 'use strict';
- var anObject = require('../internals/an-object');
- // `RegExp.prototype.flags` getter implementation
- // https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags
- module.exports = function () {
- var that = anObject(this);
- var result = '';
- if (that.global) result += 'g';
- if (that.ignoreCase) result += 'i';
- if (that.multiline) result += 'm';
- if (that.dotAll) result += 's';
- if (that.unicode) result += 'u';
- if (that.sticky) result += 'y';
- return result;
- };
- },{"../internals/an-object":55}],142:[function(require,module,exports){
- // `RequireObjectCoercible` abstract operation
- // https://tc39.github.io/ecma262/#sec-requireobjectcoercible
- module.exports = function (it) {
- if (it == undefined) throw TypeError("Can't call method on " + it);
- return it;
- };
- },{}],143:[function(require,module,exports){
- var global = require('../internals/global');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- module.exports = function (key, value) {
- try {
- createNonEnumerableProperty(global, key, value);
- } catch (error) {
- global[key] = value;
- } return value;
- };
- },{"../internals/create-non-enumerable-property":76,"../internals/global":92}],144:[function(require,module,exports){
- 'use strict';
- var getBuiltIn = require('../internals/get-built-in');
- var definePropertyModule = require('../internals/object-define-property');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var DESCRIPTORS = require('../internals/descriptors');
- var SPECIES = wellKnownSymbol('species');
- module.exports = function (CONSTRUCTOR_NAME) {
- var Constructor = getBuiltIn(CONSTRUCTOR_NAME);
- var defineProperty = definePropertyModule.f;
- if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) {
- defineProperty(Constructor, SPECIES, {
- configurable: true,
- get: function () { return this; }
- });
- }
- };
- },{"../internals/descriptors":81,"../internals/get-built-in":90,"../internals/object-define-property":120,"../internals/well-known-symbol":169}],145:[function(require,module,exports){
- var defineProperty = require('../internals/object-define-property').f;
- var has = require('../internals/has');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var TO_STRING_TAG = wellKnownSymbol('toStringTag');
- module.exports = function (it, TAG, STATIC) {
- if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {
- defineProperty(it, TO_STRING_TAG, { configurable: true, value: TAG });
- }
- };
- },{"../internals/has":93,"../internals/object-define-property":120,"../internals/well-known-symbol":169}],146:[function(require,module,exports){
- var shared = require('../internals/shared');
- var uid = require('../internals/uid');
- var keys = shared('keys');
- module.exports = function (key) {
- return keys[key] || (keys[key] = uid(key));
- };
- },{"../internals/shared":148,"../internals/uid":166}],147:[function(require,module,exports){
- var global = require('../internals/global');
- var setGlobal = require('../internals/set-global');
- var SHARED = '__core-js_shared__';
- var store = global[SHARED] || setGlobal(SHARED, {});
- module.exports = store;
- },{"../internals/global":92,"../internals/set-global":143}],148:[function(require,module,exports){
- var IS_PURE = require('../internals/is-pure');
- var store = require('../internals/shared-store');
- (module.exports = function (key, value) {
- return store[key] || (store[key] = value !== undefined ? value : {});
- })('versions', []).push({
- version: '3.4.1',
- mode: IS_PURE ? 'pure' : 'global',
- copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
- });
- },{"../internals/is-pure":106,"../internals/shared-store":147}],149:[function(require,module,exports){
- 'use strict';
- var fails = require('../internals/fails');
- module.exports = function (METHOD_NAME, argument) {
- var method = [][METHOD_NAME];
- return !method || !fails(function () {
- // eslint-disable-next-line no-useless-call,no-throw-literal
- method.call(null, argument || function () { throw 1; }, 1);
- });
- };
- },{"../internals/fails":86}],150:[function(require,module,exports){
- var anObject = require('../internals/an-object');
- var aFunction = require('../internals/a-function');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var SPECIES = wellKnownSymbol('species');
- // `SpeciesConstructor` abstract operation
- // https://tc39.github.io/ecma262/#sec-speciesconstructor
- module.exports = function (O, defaultConstructor) {
- var C = anObject(O).constructor;
- var S;
- return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? defaultConstructor : aFunction(S);
- };
- },{"../internals/a-function":50,"../internals/an-object":55,"../internals/well-known-symbol":169}],151:[function(require,module,exports){
- var toInteger = require('../internals/to-integer');
- var requireObjectCoercible = require('../internals/require-object-coercible');
- // `String.prototype.{ codePointAt, at }` methods implementation
- var createMethod = function (CONVERT_TO_STRING) {
- return function ($this, pos) {
- var S = String(requireObjectCoercible($this));
- var position = toInteger(pos);
- var size = S.length;
- var first, second;
- if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
- first = S.charCodeAt(position);
- return first < 0xD800 || first > 0xDBFF || position + 1 === size
- || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
- ? CONVERT_TO_STRING ? S.charAt(position) : first
- : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
- };
- };
- module.exports = {
- // `String.prototype.codePointAt` method
- // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
- codeAt: createMethod(false),
- // `String.prototype.at` method
- // https://github.com/mathiasbynens/String.prototype.at
- charAt: createMethod(true)
- };
- },{"../internals/require-object-coercible":142,"../internals/to-integer":157}],152:[function(require,module,exports){
- var requireObjectCoercible = require('../internals/require-object-coercible');
- var whitespaces = require('../internals/whitespaces');
- var whitespace = '[' + whitespaces + ']';
- var ltrim = RegExp('^' + whitespace + whitespace + '*');
- var rtrim = RegExp(whitespace + whitespace + '*$');
- // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
- var createMethod = function (TYPE) {
- return function ($this) {
- var string = String(requireObjectCoercible($this));
- if (TYPE & 1) string = string.replace(ltrim, '');
- if (TYPE & 2) string = string.replace(rtrim, '');
- return string;
- };
- };
- module.exports = {
- // `String.prototype.{ trimLeft, trimStart }` methods
- // https://tc39.github.io/ecma262/#sec-string.prototype.trimstart
- start: createMethod(1),
- // `String.prototype.{ trimRight, trimEnd }` methods
- // https://tc39.github.io/ecma262/#sec-string.prototype.trimend
- end: createMethod(2),
- // `String.prototype.trim` method
- // https://tc39.github.io/ecma262/#sec-string.prototype.trim
- trim: createMethod(3)
- };
- },{"../internals/require-object-coercible":142,"../internals/whitespaces":170}],153:[function(require,module,exports){
- var global = require('../internals/global');
- var fails = require('../internals/fails');
- var classof = require('../internals/classof-raw');
- var bind = require('../internals/bind-context');
- var html = require('../internals/html');
- var createElement = require('../internals/document-create-element');
- var IS_IOS = require('../internals/is-ios');
- var location = global.location;
- var set = global.setImmediate;
- var clear = global.clearImmediate;
- var process = global.process;
- var MessageChannel = global.MessageChannel;
- var Dispatch = global.Dispatch;
- var counter = 0;
- var queue = {};
- var ONREADYSTATECHANGE = 'onreadystatechange';
- var defer, channel, port;
- var run = function (id) {
- // eslint-disable-next-line no-prototype-builtins
- if (queue.hasOwnProperty(id)) {
- var fn = queue[id];
- delete queue[id];
- fn();
- }
- };
- var runner = function (id) {
- return function () {
- run(id);
- };
- };
- var listener = function (event) {
- run(event.data);
- };
- var post = function (id) {
- // old engines have not location.origin
- global.postMessage(id + '', location.protocol + '//' + location.host);
- };
- // Node.js 0.9+ & IE10+ has setImmediate, otherwise:
- if (!set || !clear) {
- set = function setImmediate(fn) {
- var args = [];
- var i = 1;
- while (arguments.length > i) args.push(arguments[i++]);
- queue[++counter] = function () {
- // eslint-disable-next-line no-new-func
- (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args);
- };
- defer(counter);
- return counter;
- };
- clear = function clearImmediate(id) {
- delete queue[id];
- };
- // Node.js 0.8-
- if (classof(process) == 'process') {
- defer = function (id) {
- process.nextTick(runner(id));
- };
- // Sphere (JS game engine) Dispatch API
- } else if (Dispatch && Dispatch.now) {
- defer = function (id) {
- Dispatch.now(runner(id));
- };
- // Browsers with MessageChannel, includes WebWorkers
- // except iOS - https://github.com/zloirock/core-js/issues/624
- } else if (MessageChannel && !IS_IOS) {
- channel = new MessageChannel();
- port = channel.port2;
- channel.port1.onmessage = listener;
- defer = bind(port.postMessage, port, 1);
- // Browsers with postMessage, skip WebWorkers
- // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
- } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts && !fails(post)) {
- defer = post;
- global.addEventListener('message', listener, false);
- // IE8-
- } else if (ONREADYSTATECHANGE in createElement('script')) {
- defer = function (id) {
- html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {
- html.removeChild(this);
- run(id);
- };
- };
- // Rest old browsers
- } else {
- defer = function (id) {
- setTimeout(runner(id), 0);
- };
- }
- }
- module.exports = {
- set: set,
- clear: clear
- };
- },{"../internals/bind-context":67,"../internals/classof-raw":70,"../internals/document-create-element":82,"../internals/fails":86,"../internals/global":92,"../internals/html":96,"../internals/is-ios":104}],154:[function(require,module,exports){
- var toInteger = require('../internals/to-integer');
- var max = Math.max;
- var min = Math.min;
- // Helper for a popular repeating case of the spec:
- // Let integer be ? ToInteger(index).
- // If integer < 0, let result be max((length + integer), 0); else let result be min(length, length).
- module.exports = function (index, length) {
- var integer = toInteger(index);
- return integer < 0 ? max(integer + length, 0) : min(integer, length);
- };
- },{"../internals/to-integer":157}],155:[function(require,module,exports){
- var toInteger = require('../internals/to-integer');
- var toLength = require('../internals/to-length');
- // `ToIndex` abstract operation
- // https://tc39.github.io/ecma262/#sec-toindex
- module.exports = function (it) {
- if (it === undefined) return 0;
- var number = toInteger(it);
- var length = toLength(number);
- if (number !== length) throw RangeError('Wrong length or index');
- return length;
- };
- },{"../internals/to-integer":157,"../internals/to-length":158}],156:[function(require,module,exports){
- // toObject with fallback for non-array-like ES3 strings
- var IndexedObject = require('../internals/indexed-object');
- var requireObjectCoercible = require('../internals/require-object-coercible');
- module.exports = function (it) {
- return IndexedObject(requireObjectCoercible(it));
- };
- },{"../internals/indexed-object":98,"../internals/require-object-coercible":142}],157:[function(require,module,exports){
- var ceil = Math.ceil;
- var floor = Math.floor;
- // `ToInteger` abstract operation
- // https://tc39.github.io/ecma262/#sec-tointeger
- module.exports = function (argument) {
- return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
- };
- },{}],158:[function(require,module,exports){
- var toInteger = require('../internals/to-integer');
- var min = Math.min;
- // `ToLength` abstract operation
- // https://tc39.github.io/ecma262/#sec-tolength
- module.exports = function (argument) {
- return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
- };
- },{"../internals/to-integer":157}],159:[function(require,module,exports){
- var requireObjectCoercible = require('../internals/require-object-coercible');
- // `ToObject` abstract operation
- // https://tc39.github.io/ecma262/#sec-toobject
- module.exports = function (argument) {
- return Object(requireObjectCoercible(argument));
- };
- },{"../internals/require-object-coercible":142}],160:[function(require,module,exports){
- var toPositiveInteger = require('../internals/to-positive-integer');
- module.exports = function (it, BYTES) {
- var offset = toPositiveInteger(it);
- if (offset % BYTES) throw RangeError('Wrong offset');
- return offset;
- };
- },{"../internals/to-positive-integer":161}],161:[function(require,module,exports){
- var toInteger = require('../internals/to-integer');
- module.exports = function (it) {
- var result = toInteger(it);
- if (result < 0) throw RangeError("The argument can't be less than 0");
- return result;
- };
- },{"../internals/to-integer":157}],162:[function(require,module,exports){
- var isObject = require('../internals/is-object');
- // `ToPrimitive` abstract operation
- // https://tc39.github.io/ecma262/#sec-toprimitive
- // instead of the ES6 spec version, we didn't implement @@toPrimitive case
- // and the second argument - flag - preferred type is a string
- module.exports = function (input, PREFERRED_STRING) {
- if (!isObject(input)) return input;
- var fn, val;
- if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
- if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
- if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
- throw TypeError("Can't convert object to primitive value");
- };
- },{"../internals/is-object":105}],163:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var global = require('../internals/global');
- var DESCRIPTORS = require('../internals/descriptors');
- var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = require('../internals/typed-arrays-constructors-requires-wrappers');
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var ArrayBufferModule = require('../internals/array-buffer');
- var anInstance = require('../internals/an-instance');
- var createPropertyDescriptor = require('../internals/create-property-descriptor');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var toLength = require('../internals/to-length');
- var toIndex = require('../internals/to-index');
- var toOffset = require('../internals/to-offset');
- var toPrimitive = require('../internals/to-primitive');
- var has = require('../internals/has');
- var classof = require('../internals/classof');
- var isObject = require('../internals/is-object');
- var create = require('../internals/object-create');
- var setPrototypeOf = require('../internals/object-set-prototype-of');
- var getOwnPropertyNames = require('../internals/object-get-own-property-names').f;
- var typedArrayFrom = require('../internals/typed-array-from');
- var forEach = require('../internals/array-iteration').forEach;
- var setSpecies = require('../internals/set-species');
- var definePropertyModule = require('../internals/object-define-property');
- var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');
- var InternalStateModule = require('../internals/internal-state');
- var inheritIfRequired = require('../internals/inherit-if-required');
- var getInternalState = InternalStateModule.get;
- var setInternalState = InternalStateModule.set;
- var nativeDefineProperty = definePropertyModule.f;
- var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
- var round = Math.round;
- var RangeError = global.RangeError;
- var ArrayBuffer = ArrayBufferModule.ArrayBuffer;
- var DataView = ArrayBufferModule.DataView;
- var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS;
- var TYPED_ARRAY_TAG = ArrayBufferViewCore.TYPED_ARRAY_TAG;
- var TypedArray = ArrayBufferViewCore.TypedArray;
- var TypedArrayPrototype = ArrayBufferViewCore.TypedArrayPrototype;
- var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
- var isTypedArray = ArrayBufferViewCore.isTypedArray;
- var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';
- var WRONG_LENGTH = 'Wrong length';
- var fromList = function (C, list) {
- var index = 0;
- var length = list.length;
- var result = new (aTypedArrayConstructor(C))(length);
- while (length > index) result[index] = list[index++];
- return result;
- };
- var addGetter = function (it, key) {
- nativeDefineProperty(it, key, { get: function () {
- return getInternalState(this)[key];
- } });
- };
- var isArrayBuffer = function (it) {
- var klass;
- return it instanceof ArrayBuffer || (klass = classof(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer';
- };
- var isTypedArrayIndex = function (target, key) {
- return isTypedArray(target)
- && typeof key != 'symbol'
- && key in target
- && String(+key) == String(key);
- };
- var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) {
- return isTypedArrayIndex(target, key = toPrimitive(key, true))
- ? createPropertyDescriptor(2, target[key])
- : nativeGetOwnPropertyDescriptor(target, key);
- };
- var wrappedDefineProperty = function defineProperty(target, key, descriptor) {
- if (isTypedArrayIndex(target, key = toPrimitive(key, true))
- && isObject(descriptor)
- && has(descriptor, 'value')
- && !has(descriptor, 'get')
- && !has(descriptor, 'set')
- // TODO: add validation descriptor w/o calling accessors
- && !descriptor.configurable
- && (!has(descriptor, 'writable') || descriptor.writable)
- && (!has(descriptor, 'enumerable') || descriptor.enumerable)
- ) {
- target[key] = descriptor.value;
- return target;
- } return nativeDefineProperty(target, key, descriptor);
- };
- if (DESCRIPTORS) {
- if (!NATIVE_ARRAY_BUFFER_VIEWS) {
- getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor;
- definePropertyModule.f = wrappedDefineProperty;
- addGetter(TypedArrayPrototype, 'buffer');
- addGetter(TypedArrayPrototype, 'byteOffset');
- addGetter(TypedArrayPrototype, 'byteLength');
- addGetter(TypedArrayPrototype, 'length');
- }
- $({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, {
- getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor,
- defineProperty: wrappedDefineProperty
- });
- module.exports = function (TYPE, BYTES, wrapper, CLAMPED) {
- var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array';
- var GETTER = 'get' + TYPE;
- var SETTER = 'set' + TYPE;
- var NativeTypedArrayConstructor = global[CONSTRUCTOR_NAME];
- var TypedArrayConstructor = NativeTypedArrayConstructor;
- var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype;
- var exported = {};
- var getter = function (that, index) {
- var data = getInternalState(that);
- return data.view[GETTER](index * BYTES + data.byteOffset, true);
- };
- var setter = function (that, index, value) {
- var data = getInternalState(that);
- if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF;
- data.view[SETTER](index * BYTES + data.byteOffset, value, true);
- };
- var addElement = function (that, index) {
- nativeDefineProperty(that, index, {
- get: function () {
- return getter(this, index);
- },
- set: function (value) {
- return setter(this, index, value);
- },
- enumerable: true
- });
- };
- if (!NATIVE_ARRAY_BUFFER_VIEWS) {
- TypedArrayConstructor = wrapper(function (that, data, offset, $length) {
- anInstance(that, TypedArrayConstructor, CONSTRUCTOR_NAME);
- var index = 0;
- var byteOffset = 0;
- var buffer, byteLength, length;
- if (!isObject(data)) {
- length = toIndex(data);
- byteLength = length * BYTES;
- buffer = new ArrayBuffer(byteLength);
- } else if (isArrayBuffer(data)) {
- buffer = data;
- byteOffset = toOffset(offset, BYTES);
- var $len = data.byteLength;
- if ($length === undefined) {
- if ($len % BYTES) throw RangeError(WRONG_LENGTH);
- byteLength = $len - byteOffset;
- if (byteLength < 0) throw RangeError(WRONG_LENGTH);
- } else {
- byteLength = toLength($length) * BYTES;
- if (byteLength + byteOffset > $len) throw RangeError(WRONG_LENGTH);
- }
- length = byteLength / BYTES;
- } else if (isTypedArray(data)) {
- return fromList(TypedArrayConstructor, data);
- } else {
- return typedArrayFrom.call(TypedArrayConstructor, data);
- }
- setInternalState(that, {
- buffer: buffer,
- byteOffset: byteOffset,
- byteLength: byteLength,
- length: length,
- view: new DataView(buffer)
- });
- while (index < length) addElement(that, index++);
- });
- if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray);
- TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create(TypedArrayPrototype);
- } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) {
- TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) {
- anInstance(dummy, TypedArrayConstructor, CONSTRUCTOR_NAME);
- return inheritIfRequired(function () {
- if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data));
- if (isArrayBuffer(data)) return $length !== undefined
- ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length)
- : typedArrayOffset !== undefined
- ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES))
- : new NativeTypedArrayConstructor(data);
- if (isTypedArray(data)) return fromList(TypedArrayConstructor, data);
- return typedArrayFrom.call(TypedArrayConstructor, data);
- }(), dummy, TypedArrayConstructor);
- });
- if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray);
- forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) {
- if (!(key in TypedArrayConstructor)) {
- createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]);
- }
- });
- TypedArrayConstructor.prototype = TypedArrayConstructorPrototype;
- }
- if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) {
- createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor);
- }
- if (TYPED_ARRAY_TAG) {
- createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME);
- }
- exported[CONSTRUCTOR_NAME] = TypedArrayConstructor;
- $({
- global: true, forced: TypedArrayConstructor != NativeTypedArrayConstructor, sham: !NATIVE_ARRAY_BUFFER_VIEWS
- }, exported);
- if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) {
- createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES);
- }
- if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) {
- createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES);
- }
- setSpecies(CONSTRUCTOR_NAME);
- };
- } else module.exports = function () { /* empty */ };
- },{"../internals/an-instance":54,"../internals/array-buffer":57,"../internals/array-buffer-view-core":56,"../internals/array-iteration":62,"../internals/classof":71,"../internals/create-non-enumerable-property":76,"../internals/create-property-descriptor":77,"../internals/descriptors":81,"../internals/export":85,"../internals/global":92,"../internals/has":93,"../internals/inherit-if-required":99,"../internals/internal-state":100,"../internals/is-object":105,"../internals/object-create":118,"../internals/object-define-property":120,"../internals/object-get-own-property-descriptor":121,"../internals/object-get-own-property-names":123,"../internals/object-set-prototype-of":129,"../internals/set-species":144,"../internals/to-index":155,"../internals/to-length":158,"../internals/to-offset":160,"../internals/to-primitive":162,"../internals/typed-array-from":164,"../internals/typed-arrays-constructors-requires-wrappers":165}],164:[function(require,module,exports){
- var toObject = require('../internals/to-object');
- var toLength = require('../internals/to-length');
- var getIteratorMethod = require('../internals/get-iterator-method');
- var isArrayIteratorMethod = require('../internals/is-array-iterator-method');
- var bind = require('../internals/bind-context');
- var aTypedArrayConstructor = require('../internals/array-buffer-view-core').aTypedArrayConstructor;
- module.exports = function from(source /* , mapfn, thisArg */) {
- var O = toObject(source);
- var argumentsLength = arguments.length;
- var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
- var mapping = mapfn !== undefined;
- var iteratorMethod = getIteratorMethod(O);
- var i, length, result, step, iterator, next;
- if (iteratorMethod != undefined && !isArrayIteratorMethod(iteratorMethod)) {
- iterator = iteratorMethod.call(O);
- next = iterator.next;
- O = [];
- while (!(step = next.call(iterator)).done) {
- O.push(step.value);
- }
- }
- if (mapping && argumentsLength > 2) {
- mapfn = bind(mapfn, arguments[2], 2);
- }
- length = toLength(O.length);
- result = new (aTypedArrayConstructor(this))(length);
- for (i = 0; length > i; i++) {
- result[i] = mapping ? mapfn(O[i], i) : O[i];
- }
- return result;
- };
- },{"../internals/array-buffer-view-core":56,"../internals/bind-context":67,"../internals/get-iterator-method":91,"../internals/is-array-iterator-method":101,"../internals/to-length":158,"../internals/to-object":159}],165:[function(require,module,exports){
- /* eslint-disable no-new */
- var global = require('../internals/global');
- var fails = require('../internals/fails');
- var checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');
- var NATIVE_ARRAY_BUFFER_VIEWS = require('../internals/array-buffer-view-core').NATIVE_ARRAY_BUFFER_VIEWS;
- var ArrayBuffer = global.ArrayBuffer;
- var Int8Array = global.Int8Array;
- module.exports = !NATIVE_ARRAY_BUFFER_VIEWS || !fails(function () {
- Int8Array(1);
- }) || !fails(function () {
- new Int8Array(-1);
- }) || !checkCorrectnessOfIteration(function (iterable) {
- new Int8Array();
- new Int8Array(null);
- new Int8Array(1.5);
- new Int8Array(iterable);
- }, true) || fails(function () {
- // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill
- return new Int8Array(new ArrayBuffer(2), 1, undefined).length !== 1;
- });
- },{"../internals/array-buffer-view-core":56,"../internals/check-correctness-of-iteration":69,"../internals/fails":86,"../internals/global":92}],166:[function(require,module,exports){
- var id = 0;
- var postfix = Math.random();
- module.exports = function (key) {
- return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
- };
- },{}],167:[function(require,module,exports){
- var getBuiltIn = require('../internals/get-built-in');
- module.exports = getBuiltIn('navigator', 'userAgent') || '';
- },{"../internals/get-built-in":90}],168:[function(require,module,exports){
- var global = require('../internals/global');
- var userAgent = require('../internals/user-agent');
- var process = global.process;
- var versions = process && process.versions;
- var v8 = versions && versions.v8;
- var match, version;
- if (v8) {
- match = v8.split('.');
- version = match[0] + match[1];
- } else if (userAgent) {
- match = userAgent.match(/Edge\/(\d+)/);
- if (!match || match[1] >= 74) {
- match = userAgent.match(/Chrome\/(\d+)/);
- if (match) version = match[1];
- }
- }
- module.exports = version && +version;
- },{"../internals/global":92,"../internals/user-agent":167}],169:[function(require,module,exports){
- var global = require('../internals/global');
- var shared = require('../internals/shared');
- var uid = require('../internals/uid');
- var NATIVE_SYMBOL = require('../internals/native-symbol');
- var Symbol = global.Symbol;
- var store = shared('wks');
- module.exports = function (name) {
- return store[name] || (store[name] = NATIVE_SYMBOL && Symbol[name]
- || (NATIVE_SYMBOL ? Symbol : uid)('Symbol.' + name));
- };
- },{"../internals/global":92,"../internals/native-symbol":113,"../internals/shared":148,"../internals/uid":166}],170:[function(require,module,exports){
- // a string of all valid unicode whitespaces
- // eslint-disable-next-line max-len
- module.exports = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
- },{}],171:[function(require,module,exports){
- exports.f = require('../internals/well-known-symbol');
- },{"../internals/well-known-symbol":169}],172:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var fails = require('../internals/fails');
- var ArrayBufferModule = require('../internals/array-buffer');
- var anObject = require('../internals/an-object');
- var toAbsoluteIndex = require('../internals/to-absolute-index');
- var toLength = require('../internals/to-length');
- var speciesConstructor = require('../internals/species-constructor');
- var ArrayBuffer = ArrayBufferModule.ArrayBuffer;
- var DataView = ArrayBufferModule.DataView;
- var nativeArrayBufferSlice = ArrayBuffer.prototype.slice;
- var INCORRECT_SLICE = fails(function () {
- return !new ArrayBuffer(2).slice(1, undefined).byteLength;
- });
- // `ArrayBuffer.prototype.slice` method
- // https://tc39.github.io/ecma262/#sec-arraybuffer.prototype.slice
- $({ target: 'ArrayBuffer', proto: true, unsafe: true, forced: INCORRECT_SLICE }, {
- slice: function slice(start, end) {
- if (nativeArrayBufferSlice !== undefined && end === undefined) {
- return nativeArrayBufferSlice.call(anObject(this), start); // FF fix
- }
- var length = anObject(this).byteLength;
- var first = toAbsoluteIndex(start, length);
- var fin = toAbsoluteIndex(end === undefined ? length : end, length);
- var result = new (speciesConstructor(this, ArrayBuffer))(toLength(fin - first));
- var viewSource = new DataView(this);
- var viewTarget = new DataView(result);
- var index = 0;
- while (first < fin) {
- viewTarget.setUint8(index++, viewSource.getUint8(first++));
- } return result;
- }
- });
- },{"../internals/an-object":55,"../internals/array-buffer":57,"../internals/export":85,"../internals/fails":86,"../internals/species-constructor":150,"../internals/to-absolute-index":154,"../internals/to-length":158}],173:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var fails = require('../internals/fails');
- var isArray = require('../internals/is-array');
- var isObject = require('../internals/is-object');
- var toObject = require('../internals/to-object');
- var toLength = require('../internals/to-length');
- var createProperty = require('../internals/create-property');
- var arraySpeciesCreate = require('../internals/array-species-create');
- var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var V8_VERSION = require('../internals/v8-version');
- var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
- var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
- var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';
- // We can't use this feature detection in V8 since it causes
- // deoptimization and serious performance degradation
- // https://github.com/zloirock/core-js/issues/679
- var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () {
- var array = [];
- array[IS_CONCAT_SPREADABLE] = false;
- return array.concat()[0] !== array;
- });
- var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
- var isConcatSpreadable = function (O) {
- if (!isObject(O)) return false;
- var spreadable = O[IS_CONCAT_SPREADABLE];
- return spreadable !== undefined ? !!spreadable : isArray(O);
- };
- var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;
- // `Array.prototype.concat` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.concat
- // with adding support of @@isConcatSpreadable and @@species
- $({ target: 'Array', proto: true, forced: FORCED }, {
- concat: function concat(arg) { // eslint-disable-line no-unused-vars
- var O = toObject(this);
- var A = arraySpeciesCreate(O, 0);
- var n = 0;
- var i, k, length, len, E;
- for (i = -1, length = arguments.length; i < length; i++) {
- E = i === -1 ? O : arguments[i];
- if (isConcatSpreadable(E)) {
- len = toLength(E.length);
- if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
- for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
- } else {
- if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
- createProperty(A, n++, E);
- }
- }
- A.length = n;
- return A;
- }
- });
- },{"../internals/array-method-has-species-support":64,"../internals/array-species-create":66,"../internals/create-property":78,"../internals/export":85,"../internals/fails":86,"../internals/is-array":102,"../internals/is-object":105,"../internals/to-length":158,"../internals/to-object":159,"../internals/v8-version":168,"../internals/well-known-symbol":169}],174:[function(require,module,exports){
- var $ = require('../internals/export');
- var fill = require('../internals/array-fill');
- var addToUnscopables = require('../internals/add-to-unscopables');
- // `Array.prototype.fill` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.fill
- $({ target: 'Array', proto: true }, {
- fill: fill
- });
- // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
- addToUnscopables('fill');
- },{"../internals/add-to-unscopables":52,"../internals/array-fill":59,"../internals/export":85}],175:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var $filter = require('../internals/array-iteration').filter;
- var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
- // `Array.prototype.filter` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.filter
- // with adding support of @@species
- $({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('filter') }, {
- filter: function filter(callbackfn /* , thisArg */) {
- return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
- }
- });
- },{"../internals/array-iteration":62,"../internals/array-method-has-species-support":64,"../internals/export":85}],176:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var $findIndex = require('../internals/array-iteration').findIndex;
- var addToUnscopables = require('../internals/add-to-unscopables');
- var FIND_INDEX = 'findIndex';
- var SKIPS_HOLES = true;
- // Shouldn't skip holes
- if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES = false; });
- // `Array.prototype.findIndex` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.findindex
- $({ target: 'Array', proto: true, forced: SKIPS_HOLES }, {
- findIndex: function findIndex(callbackfn /* , that = undefined */) {
- return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
- }
- });
- // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
- addToUnscopables(FIND_INDEX);
- },{"../internals/add-to-unscopables":52,"../internals/array-iteration":62,"../internals/export":85}],177:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var $find = require('../internals/array-iteration').find;
- var addToUnscopables = require('../internals/add-to-unscopables');
- var FIND = 'find';
- var SKIPS_HOLES = true;
- // Shouldn't skip holes
- if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; });
- // `Array.prototype.find` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.find
- $({ target: 'Array', proto: true, forced: SKIPS_HOLES }, {
- find: function find(callbackfn /* , that = undefined */) {
- return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
- }
- });
- // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
- addToUnscopables(FIND);
- },{"../internals/add-to-unscopables":52,"../internals/array-iteration":62,"../internals/export":85}],178:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var forEach = require('../internals/array-for-each');
- // `Array.prototype.forEach` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
- $({ target: 'Array', proto: true, forced: [].forEach != forEach }, {
- forEach: forEach
- });
- },{"../internals/array-for-each":60,"../internals/export":85}],179:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var $includes = require('../internals/array-includes').includes;
- var addToUnscopables = require('../internals/add-to-unscopables');
- // `Array.prototype.includes` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.includes
- $({ target: 'Array', proto: true }, {
- includes: function includes(el /* , fromIndex = 0 */) {
- return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
- }
- });
- // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
- addToUnscopables('includes');
- },{"../internals/add-to-unscopables":52,"../internals/array-includes":61,"../internals/export":85}],180:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var $indexOf = require('../internals/array-includes').indexOf;
- var sloppyArrayMethod = require('../internals/sloppy-array-method');
- var nativeIndexOf = [].indexOf;
- var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0;
- var SLOPPY_METHOD = sloppyArrayMethod('indexOf');
- // `Array.prototype.indexOf` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.indexof
- $({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || SLOPPY_METHOD }, {
- indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
- return NEGATIVE_ZERO
- // convert -0 to +0
- ? nativeIndexOf.apply(this, arguments) || 0
- : $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined);
- }
- });
- },{"../internals/array-includes":61,"../internals/export":85,"../internals/sloppy-array-method":149}],181:[function(require,module,exports){
- var $ = require('../internals/export');
- var isArray = require('../internals/is-array');
- // `Array.isArray` method
- // https://tc39.github.io/ecma262/#sec-array.isarray
- $({ target: 'Array', stat: true }, {
- isArray: isArray
- });
- },{"../internals/export":85,"../internals/is-array":102}],182:[function(require,module,exports){
- 'use strict';
- var toIndexedObject = require('../internals/to-indexed-object');
- var addToUnscopables = require('../internals/add-to-unscopables');
- var Iterators = require('../internals/iterators');
- var InternalStateModule = require('../internals/internal-state');
- var defineIterator = require('../internals/define-iterator');
- var ARRAY_ITERATOR = 'Array Iterator';
- var setInternalState = InternalStateModule.set;
- var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR);
- // `Array.prototype.entries` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.entries
- // `Array.prototype.keys` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.keys
- // `Array.prototype.values` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.values
- // `Array.prototype[@@iterator]` method
- // https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator
- // `CreateArrayIterator` internal method
- // https://tc39.github.io/ecma262/#sec-createarrayiterator
- module.exports = defineIterator(Array, 'Array', function (iterated, kind) {
- setInternalState(this, {
- type: ARRAY_ITERATOR,
- target: toIndexedObject(iterated), // target
- index: 0, // next index
- kind: kind // kind
- });
- // `%ArrayIteratorPrototype%.next` method
- // https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next
- }, function () {
- var state = getInternalState(this);
- var target = state.target;
- var kind = state.kind;
- var index = state.index++;
- if (!target || index >= target.length) {
- state.target = undefined;
- return { value: undefined, done: true };
- }
- if (kind == 'keys') return { value: index, done: false };
- if (kind == 'values') return { value: target[index], done: false };
- return { value: [index, target[index]], done: false };
- }, 'values');
- // argumentsList[@@iterator] is %ArrayProto_values%
- // https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject
- // https://tc39.github.io/ecma262/#sec-createmappedargumentsobject
- Iterators.Arguments = Iterators.Array;
- // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
- addToUnscopables('keys');
- addToUnscopables('values');
- addToUnscopables('entries');
- },{"../internals/add-to-unscopables":52,"../internals/define-iterator":79,"../internals/internal-state":100,"../internals/iterators":110,"../internals/to-indexed-object":156}],183:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var IndexedObject = require('../internals/indexed-object');
- var toIndexedObject = require('../internals/to-indexed-object');
- var sloppyArrayMethod = require('../internals/sloppy-array-method');
- var nativeJoin = [].join;
- var ES3_STRINGS = IndexedObject != Object;
- var SLOPPY_METHOD = sloppyArrayMethod('join', ',');
- // `Array.prototype.join` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.join
- $({ target: 'Array', proto: true, forced: ES3_STRINGS || SLOPPY_METHOD }, {
- join: function join(separator) {
- return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator);
- }
- });
- },{"../internals/export":85,"../internals/indexed-object":98,"../internals/sloppy-array-method":149,"../internals/to-indexed-object":156}],184:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var $map = require('../internals/array-iteration').map;
- var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
- // `Array.prototype.map` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.map
- // with adding support of @@species
- $({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('map') }, {
- map: function map(callbackfn /* , thisArg */) {
- return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
- }
- });
- },{"../internals/array-iteration":62,"../internals/array-method-has-species-support":64,"../internals/export":85}],185:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var isArray = require('../internals/is-array');
- var nativeReverse = [].reverse;
- var test = [1, 2];
- // `Array.prototype.reverse` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.reverse
- // fix for Safari 12.0 bug
- // https://bugs.webkit.org/show_bug.cgi?id=188794
- $({ target: 'Array', proto: true, forced: String(test) === String(test.reverse()) }, {
- reverse: function reverse() {
- // eslint-disable-next-line no-self-assign
- if (isArray(this)) this.length = this.length;
- return nativeReverse.call(this);
- }
- });
- },{"../internals/export":85,"../internals/is-array":102}],186:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var isObject = require('../internals/is-object');
- var isArray = require('../internals/is-array');
- var toAbsoluteIndex = require('../internals/to-absolute-index');
- var toLength = require('../internals/to-length');
- var toIndexedObject = require('../internals/to-indexed-object');
- var createProperty = require('../internals/create-property');
- var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var SPECIES = wellKnownSymbol('species');
- var nativeSlice = [].slice;
- var max = Math.max;
- // `Array.prototype.slice` method
- // https://tc39.github.io/ecma262/#sec-array.prototype.slice
- // fallback for not array-like ES3 strings and DOM objects
- $({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('slice') }, {
- slice: function slice(start, end) {
- var O = toIndexedObject(this);
- var length = toLength(O.length);
- var k = toAbsoluteIndex(start, length);
- var fin = toAbsoluteIndex(end === undefined ? length : end, length);
- // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
- var Constructor, result, n;
- if (isArray(O)) {
- Constructor = O.constructor;
- // cross-realm fallback
- if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
- Constructor = undefined;
- } else if (isObject(Constructor)) {
- Constructor = Constructor[SPECIES];
- if (Constructor === null) Constructor = undefined;
- }
- if (Constructor === Array || Constructor === undefined) {
- return nativeSlice.call(O, k, fin);
- }
- }
- result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0));
- for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
- result.length = n;
- return result;
- }
- });
- },{"../internals/array-method-has-species-support":64,"../internals/create-property":78,"../internals/export":85,"../internals/is-array":102,"../internals/is-object":105,"../internals/to-absolute-index":154,"../internals/to-indexed-object":156,"../internals/to-length":158,"../internals/well-known-symbol":169}],187:[function(require,module,exports){
- var redefine = require('../internals/redefine');
- var DatePrototype = Date.prototype;
- var INVALID_DATE = 'Invalid Date';
- var TO_STRING = 'toString';
- var nativeDateToString = DatePrototype[TO_STRING];
- var getTime = DatePrototype.getTime;
- // `Date.prototype.toString` method
- // https://tc39.github.io/ecma262/#sec-date.prototype.tostring
- if (new Date(NaN) + '' != INVALID_DATE) {
- redefine(DatePrototype, TO_STRING, function toString() {
- var value = getTime.call(this);
- // eslint-disable-next-line no-self-compare
- return value === value ? nativeDateToString.call(this) : INVALID_DATE;
- });
- }
- },{"../internals/redefine":138}],188:[function(require,module,exports){
- var $ = require('../internals/export');
- var bind = require('../internals/function-bind');
- // `Function.prototype.bind` method
- // https://tc39.github.io/ecma262/#sec-function.prototype.bind
- $({ target: 'Function', proto: true }, {
- bind: bind
- });
- },{"../internals/export":85,"../internals/function-bind":88}],189:[function(require,module,exports){
- 'use strict';
- var DESCRIPTORS = require('../internals/descriptors');
- var global = require('../internals/global');
- var isForced = require('../internals/is-forced');
- var redefine = require('../internals/redefine');
- var has = require('../internals/has');
- var classof = require('../internals/classof-raw');
- var inheritIfRequired = require('../internals/inherit-if-required');
- var toPrimitive = require('../internals/to-primitive');
- var fails = require('../internals/fails');
- var create = require('../internals/object-create');
- var getOwnPropertyNames = require('../internals/object-get-own-property-names').f;
- var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
- var defineProperty = require('../internals/object-define-property').f;
- var trim = require('../internals/string-trim').trim;
- var NUMBER = 'Number';
- var NativeNumber = global[NUMBER];
- var NumberPrototype = NativeNumber.prototype;
- // Opera ~12 has broken Object#toString
- var BROKEN_CLASSOF = classof(create(NumberPrototype)) == NUMBER;
- // `ToNumber` abstract operation
- // https://tc39.github.io/ecma262/#sec-tonumber
- var toNumber = function (argument) {
- var it = toPrimitive(argument, false);
- var first, third, radix, maxCode, digits, length, index, code;
- if (typeof it == 'string' && it.length > 2) {
- it = trim(it);
- first = it.charCodeAt(0);
- if (first === 43 || first === 45) {
- third = it.charCodeAt(2);
- if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
- } else if (first === 48) {
- switch (it.charCodeAt(1)) {
- case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i
- case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i
- default: return +it;
- }
- digits = it.slice(2);
- length = digits.length;
- for (index = 0; index < length; index++) {
- code = digits.charCodeAt(index);
- // parseInt parses a string to a first unavailable symbol
- // but ToNumber should return NaN if a string contains unavailable symbols
- if (code < 48 || code > maxCode) return NaN;
- } return parseInt(digits, radix);
- }
- } return +it;
- };
- // `Number` constructor
- // https://tc39.github.io/ecma262/#sec-number-constructor
- if (isForced(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) {
- var NumberWrapper = function Number(value) {
- var it = arguments.length < 1 ? 0 : value;
- var dummy = this;
- return dummy instanceof NumberWrapper
- // check on 1..constructor(foo) case
- && (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classof(dummy) != NUMBER)
- ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it);
- };
- for (var keys = DESCRIPTORS ? getOwnPropertyNames(NativeNumber) : (
- // ES3:
- 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
- // ES2015 (in case, if modules with ES2015 Number statics required before):
- 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
- 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
- ).split(','), j = 0, key; keys.length > j; j++) {
- if (has(NativeNumber, key = keys[j]) && !has(NumberWrapper, key)) {
- defineProperty(NumberWrapper, key, getOwnPropertyDescriptor(NativeNumber, key));
- }
- }
- NumberWrapper.prototype = NumberPrototype;
- NumberPrototype.constructor = NumberWrapper;
- redefine(global, NUMBER, NumberWrapper);
- }
- },{"../internals/classof-raw":70,"../internals/descriptors":81,"../internals/fails":86,"../internals/global":92,"../internals/has":93,"../internals/inherit-if-required":99,"../internals/is-forced":103,"../internals/object-create":118,"../internals/object-define-property":120,"../internals/object-get-own-property-descriptor":121,"../internals/object-get-own-property-names":123,"../internals/redefine":138,"../internals/string-trim":152,"../internals/to-primitive":162}],190:[function(require,module,exports){
- var $ = require('../internals/export');
- var assign = require('../internals/object-assign');
- // `Object.assign` method
- // https://tc39.github.io/ecma262/#sec-object.assign
- $({ target: 'Object', stat: true, forced: Object.assign !== assign }, {
- assign: assign
- });
- },{"../internals/export":85,"../internals/object-assign":117}],191:[function(require,module,exports){
- var $ = require('../internals/export');
- var DESCRIPTORS = require('../internals/descriptors');
- var defineProperties = require('../internals/object-define-properties');
- // `Object.defineProperties` method
- // https://tc39.github.io/ecma262/#sec-object.defineproperties
- $({ target: 'Object', stat: true, forced: !DESCRIPTORS, sham: !DESCRIPTORS }, {
- defineProperties: defineProperties
- });
- },{"../internals/descriptors":81,"../internals/export":85,"../internals/object-define-properties":119}],192:[function(require,module,exports){
- var $ = require('../internals/export');
- var DESCRIPTORS = require('../internals/descriptors');
- var objectDefinePropertyModile = require('../internals/object-define-property');
- // `Object.defineProperty` method
- // https://tc39.github.io/ecma262/#sec-object.defineproperty
- $({ target: 'Object', stat: true, forced: !DESCRIPTORS, sham: !DESCRIPTORS }, {
- defineProperty: objectDefinePropertyModile.f
- });
- },{"../internals/descriptors":81,"../internals/export":85,"../internals/object-define-property":120}],193:[function(require,module,exports){
- var $ = require('../internals/export');
- var $entries = require('../internals/object-to-array').entries;
- // `Object.entries` method
- // https://tc39.github.io/ecma262/#sec-object.entries
- $({ target: 'Object', stat: true }, {
- entries: function entries(O) {
- return $entries(O);
- }
- });
- },{"../internals/export":85,"../internals/object-to-array":130}],194:[function(require,module,exports){
- var $ = require('../internals/export');
- var fails = require('../internals/fails');
- var toIndexedObject = require('../internals/to-indexed-object');
- var nativeGetOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
- var DESCRIPTORS = require('../internals/descriptors');
- var FAILS_ON_PRIMITIVES = fails(function () { nativeGetOwnPropertyDescriptor(1); });
- var FORCED = !DESCRIPTORS || FAILS_ON_PRIMITIVES;
- // `Object.getOwnPropertyDescriptor` method
- // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
- $({ target: 'Object', stat: true, forced: FORCED, sham: !DESCRIPTORS }, {
- getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) {
- return nativeGetOwnPropertyDescriptor(toIndexedObject(it), key);
- }
- });
- },{"../internals/descriptors":81,"../internals/export":85,"../internals/fails":86,"../internals/object-get-own-property-descriptor":121,"../internals/to-indexed-object":156}],195:[function(require,module,exports){
- var $ = require('../internals/export');
- var DESCRIPTORS = require('../internals/descriptors');
- var ownKeys = require('../internals/own-keys');
- var toIndexedObject = require('../internals/to-indexed-object');
- var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');
- var createProperty = require('../internals/create-property');
- // `Object.getOwnPropertyDescriptors` method
- // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
- $({ target: 'Object', stat: true, sham: !DESCRIPTORS }, {
- getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
- var O = toIndexedObject(object);
- var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
- var keys = ownKeys(O);
- var result = {};
- var index = 0;
- var key, descriptor;
- while (keys.length > index) {
- descriptor = getOwnPropertyDescriptor(O, key = keys[index++]);
- if (descriptor !== undefined) createProperty(result, key, descriptor);
- }
- return result;
- }
- });
- },{"../internals/create-property":78,"../internals/descriptors":81,"../internals/export":85,"../internals/object-get-own-property-descriptor":121,"../internals/own-keys":132,"../internals/to-indexed-object":156}],196:[function(require,module,exports){
- var $ = require('../internals/export');
- var toObject = require('../internals/to-object');
- var nativeKeys = require('../internals/object-keys');
- var fails = require('../internals/fails');
- var FAILS_ON_PRIMITIVES = fails(function () { nativeKeys(1); });
- // `Object.keys` method
- // https://tc39.github.io/ecma262/#sec-object.keys
- $({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, {
- keys: function keys(it) {
- return nativeKeys(toObject(it));
- }
- });
- },{"../internals/export":85,"../internals/fails":86,"../internals/object-keys":127,"../internals/to-object":159}],197:[function(require,module,exports){
- var redefine = require('../internals/redefine');
- var toString = require('../internals/object-to-string');
- var ObjectPrototype = Object.prototype;
- // `Object.prototype.toString` method
- // https://tc39.github.io/ecma262/#sec-object.prototype.tostring
- if (toString !== ObjectPrototype.toString) {
- redefine(ObjectPrototype, 'toString', toString, { unsafe: true });
- }
- },{"../internals/object-to-string":131,"../internals/redefine":138}],198:[function(require,module,exports){
- var $ = require('../internals/export');
- var parseIntImplementation = require('../internals/parse-int');
- // `parseInt` method
- // https://tc39.github.io/ecma262/#sec-parseint-string-radix
- $({ global: true, forced: parseInt != parseIntImplementation }, {
- parseInt: parseIntImplementation
- });
- },{"../internals/export":85,"../internals/parse-int":133}],199:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var IS_PURE = require('../internals/is-pure');
- var global = require('../internals/global');
- var getBuiltIn = require('../internals/get-built-in');
- var NativePromise = require('../internals/native-promise-constructor');
- var redefine = require('../internals/redefine');
- var redefineAll = require('../internals/redefine-all');
- var shared = require('../internals/shared');
- var setToStringTag = require('../internals/set-to-string-tag');
- var setSpecies = require('../internals/set-species');
- var isObject = require('../internals/is-object');
- var aFunction = require('../internals/a-function');
- var anInstance = require('../internals/an-instance');
- var classof = require('../internals/classof-raw');
- var iterate = require('../internals/iterate');
- var checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');
- var speciesConstructor = require('../internals/species-constructor');
- var task = require('../internals/task').set;
- var microtask = require('../internals/microtask');
- var promiseResolve = require('../internals/promise-resolve');
- var hostReportErrors = require('../internals/host-report-errors');
- var newPromiseCapabilityModule = require('../internals/new-promise-capability');
- var perform = require('../internals/perform');
- var InternalStateModule = require('../internals/internal-state');
- var isForced = require('../internals/is-forced');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var V8_VERSION = require('../internals/v8-version');
- var SPECIES = wellKnownSymbol('species');
- var PROMISE = 'Promise';
- var getInternalState = InternalStateModule.get;
- var setInternalState = InternalStateModule.set;
- var getInternalPromiseState = InternalStateModule.getterFor(PROMISE);
- var PromiseConstructor = NativePromise;
- var TypeError = global.TypeError;
- var document = global.document;
- var process = global.process;
- var inspectSource = shared('inspectSource');
- var $fetch = getBuiltIn('fetch');
- var newPromiseCapability = newPromiseCapabilityModule.f;
- var newGenericPromiseCapability = newPromiseCapability;
- var IS_NODE = classof(process) == 'process';
- var DISPATCH_EVENT = !!(document && document.createEvent && global.dispatchEvent);
- var UNHANDLED_REJECTION = 'unhandledrejection';
- var REJECTION_HANDLED = 'rejectionhandled';
- var PENDING = 0;
- var FULFILLED = 1;
- var REJECTED = 2;
- var HANDLED = 1;
- var UNHANDLED = 2;
- var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;
- var FORCED = isForced(PROMISE, function () {
- var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor);
- // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
- // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
- // We can't detect it synchronously, so just check versions
- if (V8_VERSION === 66) return true;
- // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
- if (!GLOBAL_CORE_JS_PROMISE && !IS_NODE && typeof PromiseRejectionEvent != 'function') return true;
- // We need Promise#finally in the pure version for preventing prototype pollution
- if (IS_PURE && !PromiseConstructor.prototype['finally']) return true;
- // We can't use @@species feature detection in V8 since it causes
- // deoptimization and performance degradation
- // https://github.com/zloirock/core-js/issues/679
- if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false;
- // Detect correctness of subclassing with @@species support
- var promise = PromiseConstructor.resolve(1);
- var FakePromise = function (exec) {
- exec(function () { /* empty */ }, function () { /* empty */ });
- };
- var constructor = promise.constructor = {};
- constructor[SPECIES] = FakePromise;
- return !(promise.then(function () { /* empty */ }) instanceof FakePromise);
- });
- var INCORRECT_ITERATION = FORCED || !checkCorrectnessOfIteration(function (iterable) {
- PromiseConstructor.all(iterable)['catch'](function () { /* empty */ });
- });
- // helpers
- var isThenable = function (it) {
- var then;
- return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
- };
- var notify = function (promise, state, isReject) {
- if (state.notified) return;
- state.notified = true;
- var chain = state.reactions;
- microtask(function () {
- var value = state.value;
- var ok = state.state == FULFILLED;
- var index = 0;
- // variable length - can't use forEach
- while (chain.length > index) {
- var reaction = chain[index++];
- var handler = ok ? reaction.ok : reaction.fail;
- var resolve = reaction.resolve;
- var reject = reaction.reject;
- var domain = reaction.domain;
- var result, then, exited;
- try {
- if (handler) {
- if (!ok) {
- if (state.rejection === UNHANDLED) onHandleUnhandled(promise, state);
- state.rejection = HANDLED;
- }
- if (handler === true) result = value;
- else {
- if (domain) domain.enter();
- result = handler(value); // can throw
- if (domain) {
- domain.exit();
- exited = true;
- }
- }
- if (result === reaction.promise) {
- reject(TypeError('Promise-chain cycle'));
- } else if (then = isThenable(result)) {
- then.call(result, resolve, reject);
- } else resolve(result);
- } else reject(value);
- } catch (error) {
- if (domain && !exited) domain.exit();
- reject(error);
- }
- }
- state.reactions = [];
- state.notified = false;
- if (isReject && !state.rejection) onUnhandled(promise, state);
- });
- };
- var dispatchEvent = function (name, promise, reason) {
- var event, handler;
- if (DISPATCH_EVENT) {
- event = document.createEvent('Event');
- event.promise = promise;
- event.reason = reason;
- event.initEvent(name, false, true);
- global.dispatchEvent(event);
- } else event = { promise: promise, reason: reason };
- if (handler = global['on' + name]) handler(event);
- else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
- };
- var onUnhandled = function (promise, state) {
- task.call(global, function () {
- var value = state.value;
- var IS_UNHANDLED = isUnhandled(state);
- var result;
- if (IS_UNHANDLED) {
- result = perform(function () {
- if (IS_NODE) {
- process.emit('unhandledRejection', value, promise);
- } else dispatchEvent(UNHANDLED_REJECTION, promise, value);
- });
- // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
- state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED;
- if (result.error) throw result.value;
- }
- });
- };
- var isUnhandled = function (state) {
- return state.rejection !== HANDLED && !state.parent;
- };
- var onHandleUnhandled = function (promise, state) {
- task.call(global, function () {
- if (IS_NODE) {
- process.emit('rejectionHandled', promise);
- } else dispatchEvent(REJECTION_HANDLED, promise, state.value);
- });
- };
- var bind = function (fn, promise, state, unwrap) {
- return function (value) {
- fn(promise, state, value, unwrap);
- };
- };
- var internalReject = function (promise, state, value, unwrap) {
- if (state.done) return;
- state.done = true;
- if (unwrap) state = unwrap;
- state.value = value;
- state.state = REJECTED;
- notify(promise, state, true);
- };
- var internalResolve = function (promise, state, value, unwrap) {
- if (state.done) return;
- state.done = true;
- if (unwrap) state = unwrap;
- try {
- if (promise === value) throw TypeError("Promise can't be resolved itself");
- var then = isThenable(value);
- if (then) {
- microtask(function () {
- var wrapper = { done: false };
- try {
- then.call(value,
- bind(internalResolve, promise, wrapper, state),
- bind(internalReject, promise, wrapper, state)
- );
- } catch (error) {
- internalReject(promise, wrapper, error, state);
- }
- });
- } else {
- state.value = value;
- state.state = FULFILLED;
- notify(promise, state, false);
- }
- } catch (error) {
- internalReject(promise, { done: false }, error, state);
- }
- };
- // constructor polyfill
- if (FORCED) {
- // 25.4.3.1 Promise(executor)
- PromiseConstructor = function Promise(executor) {
- anInstance(this, PromiseConstructor, PROMISE);
- aFunction(executor);
- Internal.call(this);
- var state = getInternalState(this);
- try {
- executor(bind(internalResolve, this, state), bind(internalReject, this, state));
- } catch (error) {
- internalReject(this, state, error);
- }
- };
- // eslint-disable-next-line no-unused-vars
- Internal = function Promise(executor) {
- setInternalState(this, {
- type: PROMISE,
- done: false,
- notified: false,
- parent: false,
- reactions: [],
- rejection: false,
- state: PENDING,
- value: undefined
- });
- };
- Internal.prototype = redefineAll(PromiseConstructor.prototype, {
- // `Promise.prototype.then` method
- // https://tc39.github.io/ecma262/#sec-promise.prototype.then
- then: function then(onFulfilled, onRejected) {
- var state = getInternalPromiseState(this);
- var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor));
- reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
- reaction.fail = typeof onRejected == 'function' && onRejected;
- reaction.domain = IS_NODE ? process.domain : undefined;
- state.parent = true;
- state.reactions.push(reaction);
- if (state.state != PENDING) notify(this, state, false);
- return reaction.promise;
- },
- // `Promise.prototype.catch` method
- // https://tc39.github.io/ecma262/#sec-promise.prototype.catch
- 'catch': function (onRejected) {
- return this.then(undefined, onRejected);
- }
- });
- OwnPromiseCapability = function () {
- var promise = new Internal();
- var state = getInternalState(promise);
- this.promise = promise;
- this.resolve = bind(internalResolve, promise, state);
- this.reject = bind(internalReject, promise, state);
- };
- newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
- return C === PromiseConstructor || C === PromiseWrapper
- ? new OwnPromiseCapability(C)
- : newGenericPromiseCapability(C);
- };
- if (!IS_PURE && typeof NativePromise == 'function') {
- nativeThen = NativePromise.prototype.then;
- // wrap native Promise#then for native async functions
- redefine(NativePromise.prototype, 'then', function then(onFulfilled, onRejected) {
- var that = this;
- return new PromiseConstructor(function (resolve, reject) {
- nativeThen.call(that, resolve, reject);
- }).then(onFulfilled, onRejected);
- // https://github.com/zloirock/core-js/issues/640
- }, { unsafe: true });
- // wrap fetch result
- if (typeof $fetch == 'function') $({ global: true, enumerable: true, forced: true }, {
- // eslint-disable-next-line no-unused-vars
- fetch: function fetch(input /* , init */) {
- return promiseResolve(PromiseConstructor, $fetch.apply(global, arguments));
- }
- });
- }
- }
- $({ global: true, wrap: true, forced: FORCED }, {
- Promise: PromiseConstructor
- });
- setToStringTag(PromiseConstructor, PROMISE, false, true);
- setSpecies(PROMISE);
- PromiseWrapper = getBuiltIn(PROMISE);
- // statics
- $({ target: PROMISE, stat: true, forced: FORCED }, {
- // `Promise.reject` method
- // https://tc39.github.io/ecma262/#sec-promise.reject
- reject: function reject(r) {
- var capability = newPromiseCapability(this);
- capability.reject.call(undefined, r);
- return capability.promise;
- }
- });
- $({ target: PROMISE, stat: true, forced: IS_PURE || FORCED }, {
- // `Promise.resolve` method
- // https://tc39.github.io/ecma262/#sec-promise.resolve
- resolve: function resolve(x) {
- return promiseResolve(IS_PURE && this === PromiseWrapper ? PromiseConstructor : this, x);
- }
- });
- $({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION }, {
- // `Promise.all` method
- // https://tc39.github.io/ecma262/#sec-promise.all
- all: function all(iterable) {
- var C = this;
- var capability = newPromiseCapability(C);
- var resolve = capability.resolve;
- var reject = capability.reject;
- var result = perform(function () {
- var $promiseResolve = aFunction(C.resolve);
- var values = [];
- var counter = 0;
- var remaining = 1;
- iterate(iterable, function (promise) {
- var index = counter++;
- var alreadyCalled = false;
- values.push(undefined);
- remaining++;
- $promiseResolve.call(C, promise).then(function (value) {
- if (alreadyCalled) return;
- alreadyCalled = true;
- values[index] = value;
- --remaining || resolve(values);
- }, reject);
- });
- --remaining || resolve(values);
- });
- if (result.error) reject(result.value);
- return capability.promise;
- },
- // `Promise.race` method
- // https://tc39.github.io/ecma262/#sec-promise.race
- race: function race(iterable) {
- var C = this;
- var capability = newPromiseCapability(C);
- var reject = capability.reject;
- var result = perform(function () {
- var $promiseResolve = aFunction(C.resolve);
- iterate(iterable, function (promise) {
- $promiseResolve.call(C, promise).then(capability.resolve, reject);
- });
- });
- if (result.error) reject(result.value);
- return capability.promise;
- }
- });
- },{"../internals/a-function":50,"../internals/an-instance":54,"../internals/check-correctness-of-iteration":69,"../internals/classof-raw":70,"../internals/export":85,"../internals/get-built-in":90,"../internals/global":92,"../internals/host-report-errors":95,"../internals/internal-state":100,"../internals/is-forced":103,"../internals/is-object":105,"../internals/is-pure":106,"../internals/iterate":108,"../internals/microtask":111,"../internals/native-promise-constructor":112,"../internals/new-promise-capability":115,"../internals/perform":135,"../internals/promise-resolve":136,"../internals/redefine":138,"../internals/redefine-all":137,"../internals/set-species":144,"../internals/set-to-string-tag":145,"../internals/shared":148,"../internals/species-constructor":150,"../internals/task":153,"../internals/v8-version":168,"../internals/well-known-symbol":169}],200:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var exec = require('../internals/regexp-exec');
- $({ target: 'RegExp', proto: true, forced: /./.exec !== exec }, {
- exec: exec
- });
- },{"../internals/export":85,"../internals/regexp-exec":140}],201:[function(require,module,exports){
- 'use strict';
- var redefine = require('../internals/redefine');
- var anObject = require('../internals/an-object');
- var fails = require('../internals/fails');
- var flags = require('../internals/regexp-flags');
- var TO_STRING = 'toString';
- var RegExpPrototype = RegExp.prototype;
- var nativeToString = RegExpPrototype[TO_STRING];
- var NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; });
- // FF44- RegExp#toString has a wrong name
- var INCORRECT_NAME = nativeToString.name != TO_STRING;
- // `RegExp.prototype.toString` method
- // https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring
- if (NOT_GENERIC || INCORRECT_NAME) {
- redefine(RegExp.prototype, TO_STRING, function toString() {
- var R = anObject(this);
- var p = String(R.source);
- var rf = R.flags;
- var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? flags.call(R) : rf);
- return '/' + p + '/' + f;
- }, { unsafe: true });
- }
- },{"../internals/an-object":55,"../internals/fails":86,"../internals/redefine":138,"../internals/regexp-flags":141}],202:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var notARegExp = require('../internals/not-a-regexp');
- var requireObjectCoercible = require('../internals/require-object-coercible');
- var correctIsRegExpLogic = require('../internals/correct-is-regexp-logic');
- // `String.prototype.includes` method
- // https://tc39.github.io/ecma262/#sec-string.prototype.includes
- $({ target: 'String', proto: true, forced: !correctIsRegExpLogic('includes') }, {
- includes: function includes(searchString /* , position = 0 */) {
- return !!~String(requireObjectCoercible(this))
- .indexOf(notARegExp(searchString), arguments.length > 1 ? arguments[1] : undefined);
- }
- });
- },{"../internals/correct-is-regexp-logic":73,"../internals/export":85,"../internals/not-a-regexp":116,"../internals/require-object-coercible":142}],203:[function(require,module,exports){
- 'use strict';
- var charAt = require('../internals/string-multibyte').charAt;
- var InternalStateModule = require('../internals/internal-state');
- var defineIterator = require('../internals/define-iterator');
- var STRING_ITERATOR = 'String Iterator';
- var setInternalState = InternalStateModule.set;
- var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);
- // `String.prototype[@@iterator]` method
- // https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator
- defineIterator(String, 'String', function (iterated) {
- setInternalState(this, {
- type: STRING_ITERATOR,
- string: String(iterated),
- index: 0
- });
- // `%StringIteratorPrototype%.next` method
- // https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next
- }, function next() {
- var state = getInternalState(this);
- var string = state.string;
- var index = state.index;
- var point;
- if (index >= string.length) return { value: undefined, done: true };
- point = charAt(string, index);
- state.index += point.length;
- return { value: point, done: false };
- });
- },{"../internals/define-iterator":79,"../internals/internal-state":100,"../internals/string-multibyte":151}],204:[function(require,module,exports){
- 'use strict';
- var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');
- var anObject = require('../internals/an-object');
- var toLength = require('../internals/to-length');
- var requireObjectCoercible = require('../internals/require-object-coercible');
- var advanceStringIndex = require('../internals/advance-string-index');
- var regExpExec = require('../internals/regexp-exec-abstract');
- // @@match logic
- fixRegExpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) {
- return [
- // `String.prototype.match` method
- // https://tc39.github.io/ecma262/#sec-string.prototype.match
- function match(regexp) {
- var O = requireObjectCoercible(this);
- var matcher = regexp == undefined ? undefined : regexp[MATCH];
- return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
- },
- // `RegExp.prototype[@@match]` method
- // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match
- function (regexp) {
- var res = maybeCallNative(nativeMatch, regexp, this);
- if (res.done) return res.value;
- var rx = anObject(regexp);
- var S = String(this);
- if (!rx.global) return regExpExec(rx, S);
- var fullUnicode = rx.unicode;
- rx.lastIndex = 0;
- var A = [];
- var n = 0;
- var result;
- while ((result = regExpExec(rx, S)) !== null) {
- var matchStr = String(result[0]);
- A[n] = matchStr;
- if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
- n++;
- }
- return n === 0 ? null : A;
- }
- ];
- });
- },{"../internals/advance-string-index":53,"../internals/an-object":55,"../internals/fix-regexp-well-known-symbol-logic":87,"../internals/regexp-exec-abstract":139,"../internals/require-object-coercible":142,"../internals/to-length":158}],205:[function(require,module,exports){
- 'use strict';
- var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');
- var anObject = require('../internals/an-object');
- var toObject = require('../internals/to-object');
- var toLength = require('../internals/to-length');
- var toInteger = require('../internals/to-integer');
- var requireObjectCoercible = require('../internals/require-object-coercible');
- var advanceStringIndex = require('../internals/advance-string-index');
- var regExpExec = require('../internals/regexp-exec-abstract');
- var max = Math.max;
- var min = Math.min;
- var floor = Math.floor;
- var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g;
- var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g;
- var maybeToString = function (it) {
- return it === undefined ? it : String(it);
- };
- // @@replace logic
- fixRegExpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative) {
- return [
- // `String.prototype.replace` method
- // https://tc39.github.io/ecma262/#sec-string.prototype.replace
- function replace(searchValue, replaceValue) {
- var O = requireObjectCoercible(this);
- var replacer = searchValue == undefined ? undefined : searchValue[REPLACE];
- return replacer !== undefined
- ? replacer.call(searchValue, O, replaceValue)
- : nativeReplace.call(String(O), searchValue, replaceValue);
- },
- // `RegExp.prototype[@@replace]` method
- // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace
- function (regexp, replaceValue) {
- var res = maybeCallNative(nativeReplace, regexp, this, replaceValue);
- if (res.done) return res.value;
- var rx = anObject(regexp);
- var S = String(this);
- var functionalReplace = typeof replaceValue === 'function';
- if (!functionalReplace) replaceValue = String(replaceValue);
- var global = rx.global;
- if (global) {
- var fullUnicode = rx.unicode;
- rx.lastIndex = 0;
- }
- var results = [];
- while (true) {
- var result = regExpExec(rx, S);
- if (result === null) break;
- results.push(result);
- if (!global) break;
- var matchStr = String(result[0]);
- if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
- }
- var accumulatedResult = '';
- var nextSourcePosition = 0;
- for (var i = 0; i < results.length; i++) {
- result = results[i];
- var matched = String(result[0]);
- var position = max(min(toInteger(result.index), S.length), 0);
- var captures = [];
- // NOTE: This is equivalent to
- // captures = result.slice(1).map(maybeToString)
- // but for some reason `nativeSlice.call(result, 1, result.length)` (called in
- // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
- // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
- for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
- var namedCaptures = result.groups;
- if (functionalReplace) {
- var replacerArgs = [matched].concat(captures, position, S);
- if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
- var replacement = String(replaceValue.apply(undefined, replacerArgs));
- } else {
- replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
- }
- if (position >= nextSourcePosition) {
- accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
- nextSourcePosition = position + matched.length;
- }
- }
- return accumulatedResult + S.slice(nextSourcePosition);
- }
- ];
- // https://tc39.github.io/ecma262/#sec-getsubstitution
- function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
- var tailPos = position + matched.length;
- var m = captures.length;
- var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
- if (namedCaptures !== undefined) {
- namedCaptures = toObject(namedCaptures);
- symbols = SUBSTITUTION_SYMBOLS;
- }
- return nativeReplace.call(replacement, symbols, function (match, ch) {
- var capture;
- switch (ch.charAt(0)) {
- case '$': return '$';
- case '&': return matched;
- case '`': return str.slice(0, position);
- case "'": return str.slice(tailPos);
- case '<':
- capture = namedCaptures[ch.slice(1, -1)];
- break;
- default: // \d\d?
- var n = +ch;
- if (n === 0) return match;
- if (n > m) {
- var f = floor(n / 10);
- if (f === 0) return match;
- if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
- return match;
- }
- capture = captures[n - 1];
- }
- return capture === undefined ? '' : capture;
- });
- }
- });
- },{"../internals/advance-string-index":53,"../internals/an-object":55,"../internals/fix-regexp-well-known-symbol-logic":87,"../internals/regexp-exec-abstract":139,"../internals/require-object-coercible":142,"../internals/to-integer":157,"../internals/to-length":158,"../internals/to-object":159}],206:[function(require,module,exports){
- 'use strict';
- var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');
- var isRegExp = require('../internals/is-regexp');
- var anObject = require('../internals/an-object');
- var requireObjectCoercible = require('../internals/require-object-coercible');
- var speciesConstructor = require('../internals/species-constructor');
- var advanceStringIndex = require('../internals/advance-string-index');
- var toLength = require('../internals/to-length');
- var callRegExpExec = require('../internals/regexp-exec-abstract');
- var regexpExec = require('../internals/regexp-exec');
- var fails = require('../internals/fails');
- var arrayPush = [].push;
- var min = Math.min;
- var MAX_UINT32 = 0xFFFFFFFF;
- // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError
- var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); });
- // @@split logic
- fixRegExpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) {
- var internalSplit;
- if (
- 'abbc'.split(/(b)*/)[1] == 'c' ||
- 'test'.split(/(?:)/, -1).length != 4 ||
- 'ab'.split(/(?:ab)*/).length != 2 ||
- '.'.split(/(.?)(.?)/).length != 4 ||
- '.'.split(/()()/).length > 1 ||
- ''.split(/.?/).length
- ) {
- // based on es5-shim implementation, need to rework it
- internalSplit = function (separator, limit) {
- var string = String(requireObjectCoercible(this));
- var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
- if (lim === 0) return [];
- if (separator === undefined) return [string];
- // If `separator` is not a regex, use native split
- if (!isRegExp(separator)) {
- return nativeSplit.call(string, separator, lim);
- }
- var output = [];
- var flags = (separator.ignoreCase ? 'i' : '') +
- (separator.multiline ? 'm' : '') +
- (separator.unicode ? 'u' : '') +
- (separator.sticky ? 'y' : '');
- var lastLastIndex = 0;
- // Make `global` and avoid `lastIndex` issues by working with a copy
- var separatorCopy = new RegExp(separator.source, flags + 'g');
- var match, lastIndex, lastLength;
- while (match = regexpExec.call(separatorCopy, string)) {
- lastIndex = separatorCopy.lastIndex;
- if (lastIndex > lastLastIndex) {
- output.push(string.slice(lastLastIndex, match.index));
- if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1));
- lastLength = match[0].length;
- lastLastIndex = lastIndex;
- if (output.length >= lim) break;
- }
- if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop
- }
- if (lastLastIndex === string.length) {
- if (lastLength || !separatorCopy.test('')) output.push('');
- } else output.push(string.slice(lastLastIndex));
- return output.length > lim ? output.slice(0, lim) : output;
- };
- // Chakra, V8
- } else if ('0'.split(undefined, 0).length) {
- internalSplit = function (separator, limit) {
- return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit);
- };
- } else internalSplit = nativeSplit;
- return [
- // `String.prototype.split` method
- // https://tc39.github.io/ecma262/#sec-string.prototype.split
- function split(separator, limit) {
- var O = requireObjectCoercible(this);
- var splitter = separator == undefined ? undefined : separator[SPLIT];
- return splitter !== undefined
- ? splitter.call(separator, O, limit)
- : internalSplit.call(String(O), separator, limit);
- },
- // `RegExp.prototype[@@split]` method
- // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split
- //
- // NOTE: This cannot be properly polyfilled in engines that don't support
- // the 'y' flag.
- function (regexp, limit) {
- var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit);
- if (res.done) return res.value;
- var rx = anObject(regexp);
- var S = String(this);
- var C = speciesConstructor(rx, RegExp);
- var unicodeMatching = rx.unicode;
- var flags = (rx.ignoreCase ? 'i' : '') +
- (rx.multiline ? 'm' : '') +
- (rx.unicode ? 'u' : '') +
- (SUPPORTS_Y ? 'y' : 'g');
- // ^(? + rx + ) is needed, in combination with some S slicing, to
- // simulate the 'y' flag.
- var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags);
- var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
- if (lim === 0) return [];
- if (S.length === 0) return callRegExpExec(splitter, S) === null ? [S] : [];
- var p = 0;
- var q = 0;
- var A = [];
- while (q < S.length) {
- splitter.lastIndex = SUPPORTS_Y ? q : 0;
- var z = callRegExpExec(splitter, SUPPORTS_Y ? S : S.slice(q));
- var e;
- if (
- z === null ||
- (e = min(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p
- ) {
- q = advanceStringIndex(S, q, unicodeMatching);
- } else {
- A.push(S.slice(p, q));
- if (A.length === lim) return A;
- for (var i = 1; i <= z.length - 1; i++) {
- A.push(z[i]);
- if (A.length === lim) return A;
- }
- q = p = e;
- }
- }
- A.push(S.slice(p));
- return A;
- }
- ];
- }, !SUPPORTS_Y);
- },{"../internals/advance-string-index":53,"../internals/an-object":55,"../internals/fails":86,"../internals/fix-regexp-well-known-symbol-logic":87,"../internals/is-regexp":107,"../internals/regexp-exec":140,"../internals/regexp-exec-abstract":139,"../internals/require-object-coercible":142,"../internals/species-constructor":150,"../internals/to-length":158}],207:[function(require,module,exports){
- 'use strict';
- var $ = require('../internals/export');
- var global = require('../internals/global');
- var getBuiltIn = require('../internals/get-built-in');
- var IS_PURE = require('../internals/is-pure');
- var DESCRIPTORS = require('../internals/descriptors');
- var NATIVE_SYMBOL = require('../internals/native-symbol');
- var fails = require('../internals/fails');
- var has = require('../internals/has');
- var isArray = require('../internals/is-array');
- var isObject = require('../internals/is-object');
- var anObject = require('../internals/an-object');
- var toObject = require('../internals/to-object');
- var toIndexedObject = require('../internals/to-indexed-object');
- var toPrimitive = require('../internals/to-primitive');
- var createPropertyDescriptor = require('../internals/create-property-descriptor');
- var nativeObjectCreate = require('../internals/object-create');
- var objectKeys = require('../internals/object-keys');
- var getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');
- var getOwnPropertyNamesExternal = require('../internals/object-get-own-property-names-external');
- var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');
- var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');
- var definePropertyModule = require('../internals/object-define-property');
- var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var redefine = require('../internals/redefine');
- var shared = require('../internals/shared');
- var sharedKey = require('../internals/shared-key');
- var hiddenKeys = require('../internals/hidden-keys');
- var uid = require('../internals/uid');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var wrappedWellKnownSymbolModule = require('../internals/wrapped-well-known-symbol');
- var defineWellKnownSymbol = require('../internals/define-well-known-symbol');
- var setToStringTag = require('../internals/set-to-string-tag');
- var InternalStateModule = require('../internals/internal-state');
- var $forEach = require('../internals/array-iteration').forEach;
- var HIDDEN = sharedKey('hidden');
- var SYMBOL = 'Symbol';
- var PROTOTYPE = 'prototype';
- var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
- var setInternalState = InternalStateModule.set;
- var getInternalState = InternalStateModule.getterFor(SYMBOL);
- var ObjectPrototype = Object[PROTOTYPE];
- var $Symbol = global.Symbol;
- var $stringify = getBuiltIn('JSON', 'stringify');
- var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
- var nativeDefineProperty = definePropertyModule.f;
- var nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f;
- var nativePropertyIsEnumerable = propertyIsEnumerableModule.f;
- var AllSymbols = shared('symbols');
- var ObjectPrototypeSymbols = shared('op-symbols');
- var StringToSymbolRegistry = shared('string-to-symbol-registry');
- var SymbolToStringRegistry = shared('symbol-to-string-registry');
- var WellKnownSymbolsStore = shared('wks');
- var QObject = global.QObject;
- // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
- var USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
- // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
- var setSymbolDescriptor = DESCRIPTORS && fails(function () {
- return nativeObjectCreate(nativeDefineProperty({}, 'a', {
- get: function () { return nativeDefineProperty(this, 'a', { value: 7 }).a; }
- })).a != 7;
- }) ? function (O, P, Attributes) {
- var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P);
- if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];
- nativeDefineProperty(O, P, Attributes);
- if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {
- nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor);
- }
- } : nativeDefineProperty;
- var wrap = function (tag, description) {
- var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol[PROTOTYPE]);
- setInternalState(symbol, {
- type: SYMBOL,
- tag: tag,
- description: description
- });
- if (!DESCRIPTORS) symbol.description = description;
- return symbol;
- };
- var isSymbol = NATIVE_SYMBOL && typeof $Symbol.iterator == 'symbol' ? function (it) {
- return typeof it == 'symbol';
- } : function (it) {
- return Object(it) instanceof $Symbol;
- };
- var $defineProperty = function defineProperty(O, P, Attributes) {
- if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);
- anObject(O);
- var key = toPrimitive(P, true);
- anObject(Attributes);
- if (has(AllSymbols, key)) {
- if (!Attributes.enumerable) {
- if (!has(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {}));
- O[HIDDEN][key] = true;
- } else {
- if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
- Attributes = nativeObjectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });
- } return setSymbolDescriptor(O, key, Attributes);
- } return nativeDefineProperty(O, key, Attributes);
- };
- var $defineProperties = function defineProperties(O, Properties) {
- anObject(O);
- var properties = toIndexedObject(Properties);
- var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));
- $forEach(keys, function (key) {
- if (!DESCRIPTORS || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);
- });
- return O;
- };
- var $create = function create(O, Properties) {
- return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties);
- };
- var $propertyIsEnumerable = function propertyIsEnumerable(V) {
- var P = toPrimitive(V, true);
- var enumerable = nativePropertyIsEnumerable.call(this, P);
- if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false;
- return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;
- };
- var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {
- var it = toIndexedObject(O);
- var key = toPrimitive(P, true);
- if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return;
- var descriptor = nativeGetOwnPropertyDescriptor(it, key);
- if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) {
- descriptor.enumerable = true;
- }
- return descriptor;
- };
- var $getOwnPropertyNames = function getOwnPropertyNames(O) {
- var names = nativeGetOwnPropertyNames(toIndexedObject(O));
- var result = [];
- $forEach(names, function (key) {
- if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key);
- });
- return result;
- };
- var $getOwnPropertySymbols = function getOwnPropertySymbols(O) {
- var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;
- var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));
- var result = [];
- $forEach(names, function (key) {
- if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) {
- result.push(AllSymbols[key]);
- }
- });
- return result;
- };
- // `Symbol` constructor
- // https://tc39.github.io/ecma262/#sec-symbol-constructor
- if (!NATIVE_SYMBOL) {
- $Symbol = function Symbol() {
- if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');
- var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);
- var tag = uid(description);
- var setter = function (value) {
- if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);
- if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
- setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));
- };
- if (DESCRIPTORS && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter });
- return wrap(tag, description);
- };
- redefine($Symbol[PROTOTYPE], 'toString', function toString() {
- return getInternalState(this).tag;
- });
- propertyIsEnumerableModule.f = $propertyIsEnumerable;
- definePropertyModule.f = $defineProperty;
- getOwnPropertyDescriptorModule.f = $getOwnPropertyDescriptor;
- getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames;
- getOwnPropertySymbolsModule.f = $getOwnPropertySymbols;
- if (DESCRIPTORS) {
- // https://github.com/tc39/proposal-Symbol-description
- nativeDefineProperty($Symbol[PROTOTYPE], 'description', {
- configurable: true,
- get: function description() {
- return getInternalState(this).description;
- }
- });
- if (!IS_PURE) {
- redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });
- }
- }
- wrappedWellKnownSymbolModule.f = function (name) {
- return wrap(wellKnownSymbol(name), name);
- };
- }
- $({ global: true, wrap: true, forced: !NATIVE_SYMBOL, sham: !NATIVE_SYMBOL }, {
- Symbol: $Symbol
- });
- $forEach(objectKeys(WellKnownSymbolsStore), function (name) {
- defineWellKnownSymbol(name);
- });
- $({ target: SYMBOL, stat: true, forced: !NATIVE_SYMBOL }, {
- // `Symbol.for` method
- // https://tc39.github.io/ecma262/#sec-symbol.for
- 'for': function (key) {
- var string = String(key);
- if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
- var symbol = $Symbol(string);
- StringToSymbolRegistry[string] = symbol;
- SymbolToStringRegistry[symbol] = string;
- return symbol;
- },
- // `Symbol.keyFor` method
- // https://tc39.github.io/ecma262/#sec-symbol.keyfor
- keyFor: function keyFor(sym) {
- if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');
- if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];
- },
- useSetter: function () { USE_SETTER = true; },
- useSimple: function () { USE_SETTER = false; }
- });
- $({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL, sham: !DESCRIPTORS }, {
- // `Object.create` method
- // https://tc39.github.io/ecma262/#sec-object.create
- create: $create,
- // `Object.defineProperty` method
- // https://tc39.github.io/ecma262/#sec-object.defineproperty
- defineProperty: $defineProperty,
- // `Object.defineProperties` method
- // https://tc39.github.io/ecma262/#sec-object.defineproperties
- defineProperties: $defineProperties,
- // `Object.getOwnPropertyDescriptor` method
- // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
- getOwnPropertyDescriptor: $getOwnPropertyDescriptor
- });
- $({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL }, {
- // `Object.getOwnPropertyNames` method
- // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
- getOwnPropertyNames: $getOwnPropertyNames,
- // `Object.getOwnPropertySymbols` method
- // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols
- getOwnPropertySymbols: $getOwnPropertySymbols
- });
- // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
- // https://bugs.chromium.org/p/v8/issues/detail?id=3443
- $({ target: 'Object', stat: true, forced: fails(function () { getOwnPropertySymbolsModule.f(1); }) }, {
- getOwnPropertySymbols: function getOwnPropertySymbols(it) {
- return getOwnPropertySymbolsModule.f(toObject(it));
- }
- });
- // `JSON.stringify` method behavior with symbols
- // https://tc39.github.io/ecma262/#sec-json.stringify
- if ($stringify) {
- var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails(function () {
- var symbol = $Symbol();
- // MS Edge converts symbol values to JSON as {}
- return $stringify([symbol]) != '[null]'
- // WebKit converts symbol values to JSON as null
- || $stringify({ a: symbol }) != '{}'
- // V8 throws on boxed symbols
- || $stringify(Object(symbol)) != '{}';
- });
- $({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, {
- // eslint-disable-next-line no-unused-vars
- stringify: function stringify(it, replacer, space) {
- var args = [it];
- var index = 1;
- var $replacer;
- while (arguments.length > index) args.push(arguments[index++]);
- $replacer = replacer;
- if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
- if (!isArray(replacer)) replacer = function (key, value) {
- if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
- if (!isSymbol(value)) return value;
- };
- args[1] = replacer;
- return $stringify.apply(null, args);
- }
- });
- }
- // `Symbol.prototype[@@toPrimitive]` method
- // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive
- if (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) {
- createNonEnumerableProperty($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
- }
- // `Symbol.prototype[@@toStringTag]` property
- // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag
- setToStringTag($Symbol, SYMBOL);
- hiddenKeys[HIDDEN] = true;
- },{"../internals/an-object":55,"../internals/array-iteration":62,"../internals/create-non-enumerable-property":76,"../internals/create-property-descriptor":77,"../internals/define-well-known-symbol":80,"../internals/descriptors":81,"../internals/export":85,"../internals/fails":86,"../internals/get-built-in":90,"../internals/global":92,"../internals/has":93,"../internals/hidden-keys":94,"../internals/internal-state":100,"../internals/is-array":102,"../internals/is-object":105,"../internals/is-pure":106,"../internals/native-symbol":113,"../internals/object-create":118,"../internals/object-define-property":120,"../internals/object-get-own-property-descriptor":121,"../internals/object-get-own-property-names":123,"../internals/object-get-own-property-names-external":122,"../internals/object-get-own-property-symbols":124,"../internals/object-keys":127,"../internals/object-property-is-enumerable":128,"../internals/redefine":138,"../internals/set-to-string-tag":145,"../internals/shared":148,"../internals/shared-key":146,"../internals/to-indexed-object":156,"../internals/to-object":159,"../internals/to-primitive":162,"../internals/uid":166,"../internals/well-known-symbol":169,"../internals/wrapped-well-known-symbol":171}],208:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $copyWithin = require('../internals/array-copy-within');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.copyWithin` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.copywithin
- ArrayBufferViewCore.exportProto('copyWithin', function copyWithin(target, start /* , end */) {
- return $copyWithin.call(aTypedArray(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-copy-within":58}],209:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $every = require('../internals/array-iteration').every;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.every` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.every
- ArrayBufferViewCore.exportProto('every', function every(callbackfn /* , thisArg */) {
- return $every(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62}],210:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $fill = require('../internals/array-fill');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.fill` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill
- // eslint-disable-next-line no-unused-vars
- ArrayBufferViewCore.exportProto('fill', function fill(value /* , start, end */) {
- return $fill.apply(aTypedArray(this), arguments);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-fill":59}],211:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $filter = require('../internals/array-iteration').filter;
- var speciesConstructor = require('../internals/species-constructor');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
- // `%TypedArray%.prototype.filter` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.filter
- ArrayBufferViewCore.exportProto('filter', function filter(callbackfn /* , thisArg */) {
- var list = $filter(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
- var C = speciesConstructor(this, this.constructor);
- var index = 0;
- var length = list.length;
- var result = new (aTypedArrayConstructor(C))(length);
- while (length > index) result[index] = list[index++];
- return result;
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62,"../internals/species-constructor":150}],212:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $findIndex = require('../internals/array-iteration').findIndex;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.findIndex` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.findindex
- ArrayBufferViewCore.exportProto('findIndex', function findIndex(predicate /* , thisArg */) {
- return $findIndex(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62}],213:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $find = require('../internals/array-iteration').find;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.find` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.find
- ArrayBufferViewCore.exportProto('find', function find(predicate /* , thisArg */) {
- return $find(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62}],214:[function(require,module,exports){
- var typedArrayConstructor = require('../internals/typed-array-constructor');
- // `Float32Array` constructor
- // https://tc39.github.io/ecma262/#sec-typedarray-objects
- typedArrayConstructor('Float32', 4, function (init) {
- return function Float32Array(data, byteOffset, length) {
- return init(this, data, byteOffset, length);
- };
- });
- },{"../internals/typed-array-constructor":163}],215:[function(require,module,exports){
- var typedArrayConstructor = require('../internals/typed-array-constructor');
- // `Float64Array` constructor
- // https://tc39.github.io/ecma262/#sec-typedarray-objects
- typedArrayConstructor('Float64', 8, function (init) {
- return function Float64Array(data, byteOffset, length) {
- return init(this, data, byteOffset, length);
- };
- });
- },{"../internals/typed-array-constructor":163}],216:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $forEach = require('../internals/array-iteration').forEach;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.forEach` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.foreach
- ArrayBufferViewCore.exportProto('forEach', function forEach(callbackfn /* , thisArg */) {
- $forEach(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62}],217:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $includes = require('../internals/array-includes').includes;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.includes` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.includes
- ArrayBufferViewCore.exportProto('includes', function includes(searchElement /* , fromIndex */) {
- return $includes(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-includes":61}],218:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $indexOf = require('../internals/array-includes').indexOf;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.indexOf` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.indexof
- ArrayBufferViewCore.exportProto('indexOf', function indexOf(searchElement /* , fromIndex */) {
- return $indexOf(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-includes":61}],219:[function(require,module,exports){
- 'use strict';
- var global = require('../internals/global');
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var ArrayIterators = require('../modules/es.array.iterator');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var ITERATOR = wellKnownSymbol('iterator');
- var Uint8Array = global.Uint8Array;
- var arrayValues = ArrayIterators.values;
- var arrayKeys = ArrayIterators.keys;
- var arrayEntries = ArrayIterators.entries;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- var exportProto = ArrayBufferViewCore.exportProto;
- var nativeTypedArrayIterator = Uint8Array && Uint8Array.prototype[ITERATOR];
- var CORRECT_ITER_NAME = !!nativeTypedArrayIterator
- && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined);
- var typedArrayValues = function values() {
- return arrayValues.call(aTypedArray(this));
- };
- // `%TypedArray%.prototype.entries` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.entries
- exportProto('entries', function entries() {
- return arrayEntries.call(aTypedArray(this));
- });
- // `%TypedArray%.prototype.keys` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.keys
- exportProto('keys', function keys() {
- return arrayKeys.call(aTypedArray(this));
- });
- // `%TypedArray%.prototype.values` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.values
- exportProto('values', typedArrayValues, !CORRECT_ITER_NAME);
- // `%TypedArray%.prototype[@@iterator]` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype-@@iterator
- exportProto(ITERATOR, typedArrayValues, !CORRECT_ITER_NAME);
- },{"../internals/array-buffer-view-core":56,"../internals/global":92,"../internals/well-known-symbol":169,"../modules/es.array.iterator":182}],220:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- var $join = [].join;
- // `%TypedArray%.prototype.join` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join
- // eslint-disable-next-line no-unused-vars
- ArrayBufferViewCore.exportProto('join', function join(separator) {
- return $join.apply(aTypedArray(this), arguments);
- });
- },{"../internals/array-buffer-view-core":56}],221:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $lastIndexOf = require('../internals/array-last-index-of');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.lastIndexOf` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.lastindexof
- // eslint-disable-next-line no-unused-vars
- ArrayBufferViewCore.exportProto('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */) {
- return $lastIndexOf.apply(aTypedArray(this), arguments);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-last-index-of":63}],222:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $map = require('../internals/array-iteration').map;
- var speciesConstructor = require('../internals/species-constructor');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
- // `%TypedArray%.prototype.map` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.map
- ArrayBufferViewCore.exportProto('map', function map(mapfn /* , thisArg */) {
- return $map(aTypedArray(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) {
- return new (aTypedArrayConstructor(speciesConstructor(O, O.constructor)))(length);
- });
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62,"../internals/species-constructor":150}],223:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $reduceRight = require('../internals/array-reduce').right;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.reduceRicht` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduceright
- ArrayBufferViewCore.exportProto('reduceRight', function reduceRight(callbackfn /* , initialValue */) {
- return $reduceRight(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-reduce":65}],224:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $reduce = require('../internals/array-reduce').left;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.reduce` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduce
- ArrayBufferViewCore.exportProto('reduce', function reduce(callbackfn /* , initialValue */) {
- return $reduce(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-reduce":65}],225:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- var floor = Math.floor;
- // `%TypedArray%.prototype.reverse` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reverse
- ArrayBufferViewCore.exportProto('reverse', function reverse() {
- var that = this;
- var length = aTypedArray(that).length;
- var middle = floor(length / 2);
- var index = 0;
- var value;
- while (index < middle) {
- value = that[index];
- that[index++] = that[--length];
- that[length] = value;
- } return that;
- });
- },{"../internals/array-buffer-view-core":56}],226:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var toLength = require('../internals/to-length');
- var toOffset = require('../internals/to-offset');
- var toObject = require('../internals/to-object');
- var fails = require('../internals/fails');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- var FORCED = fails(function () {
- // eslint-disable-next-line no-undef
- new Int8Array(1).set({});
- });
- // `%TypedArray%.prototype.set` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.set
- ArrayBufferViewCore.exportProto('set', function set(arrayLike /* , offset */) {
- aTypedArray(this);
- var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1);
- var length = this.length;
- var src = toObject(arrayLike);
- var len = toLength(src.length);
- var index = 0;
- if (len + offset > length) throw RangeError('Wrong length');
- while (index < len) this[offset + index] = src[index++];
- }, FORCED);
- },{"../internals/array-buffer-view-core":56,"../internals/fails":86,"../internals/to-length":158,"../internals/to-object":159,"../internals/to-offset":160}],227:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var speciesConstructor = require('../internals/species-constructor');
- var fails = require('../internals/fails');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;
- var $slice = [].slice;
- var FORCED = fails(function () {
- // eslint-disable-next-line no-undef
- new Int8Array(1).slice();
- });
- // `%TypedArray%.prototype.slice` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.slice
- ArrayBufferViewCore.exportProto('slice', function slice(start, end) {
- var list = $slice.call(aTypedArray(this), start, end);
- var C = speciesConstructor(this, this.constructor);
- var index = 0;
- var length = list.length;
- var result = new (aTypedArrayConstructor(C))(length);
- while (length > index) result[index] = list[index++];
- return result;
- }, FORCED);
- },{"../internals/array-buffer-view-core":56,"../internals/fails":86,"../internals/species-constructor":150}],228:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var $some = require('../internals/array-iteration').some;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.some` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some
- ArrayBufferViewCore.exportProto('some', function some(callbackfn /* , thisArg */) {
- return $some(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
- });
- },{"../internals/array-buffer-view-core":56,"../internals/array-iteration":62}],229:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- var $sort = [].sort;
- // `%TypedArray%.prototype.sort` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.sort
- ArrayBufferViewCore.exportProto('sort', function sort(comparefn) {
- return $sort.call(aTypedArray(this), comparefn);
- });
- },{"../internals/array-buffer-view-core":56}],230:[function(require,module,exports){
- 'use strict';
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var toLength = require('../internals/to-length');
- var toAbsoluteIndex = require('../internals/to-absolute-index');
- var speciesConstructor = require('../internals/species-constructor');
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- // `%TypedArray%.prototype.subarray` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.subarray
- ArrayBufferViewCore.exportProto('subarray', function subarray(begin, end) {
- var O = aTypedArray(this);
- var length = O.length;
- var beginIndex = toAbsoluteIndex(begin, length);
- return new (speciesConstructor(O, O.constructor))(
- O.buffer,
- O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT,
- toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - beginIndex)
- );
- });
- },{"../internals/array-buffer-view-core":56,"../internals/species-constructor":150,"../internals/to-absolute-index":154,"../internals/to-length":158}],231:[function(require,module,exports){
- 'use strict';
- var global = require('../internals/global');
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var fails = require('../internals/fails');
- var Int8Array = global.Int8Array;
- var aTypedArray = ArrayBufferViewCore.aTypedArray;
- var $toLocaleString = [].toLocaleString;
- var $slice = [].slice;
- // iOS Safari 6.x fails here
- var TO_LOCALE_STRING_BUG = !!Int8Array && fails(function () {
- $toLocaleString.call(new Int8Array(1));
- });
- var FORCED = fails(function () {
- return [1, 2].toLocaleString() != new Int8Array([1, 2]).toLocaleString();
- }) || !fails(function () {
- Int8Array.prototype.toLocaleString.call([1, 2]);
- });
- // `%TypedArray%.prototype.toLocaleString` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tolocalestring
- ArrayBufferViewCore.exportProto('toLocaleString', function toLocaleString() {
- return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray(this)) : aTypedArray(this), arguments);
- }, FORCED);
- },{"../internals/array-buffer-view-core":56,"../internals/fails":86,"../internals/global":92}],232:[function(require,module,exports){
- 'use strict';
- var global = require('../internals/global');
- var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
- var fails = require('../internals/fails');
- var Uint8Array = global.Uint8Array;
- var Uint8ArrayPrototype = Uint8Array && Uint8Array.prototype;
- var arrayToString = [].toString;
- var arrayJoin = [].join;
- if (fails(function () { arrayToString.call({}); })) {
- arrayToString = function toString() {
- return arrayJoin.call(this);
- };
- }
- // `%TypedArray%.prototype.toString` method
- // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tostring
- ArrayBufferViewCore.exportProto('toString', arrayToString, (Uint8ArrayPrototype || {}).toString != arrayToString);
- },{"../internals/array-buffer-view-core":56,"../internals/fails":86,"../internals/global":92}],233:[function(require,module,exports){
- var typedArrayConstructor = require('../internals/typed-array-constructor');
- // `Uint8Array` constructor
- // https://tc39.github.io/ecma262/#sec-typedarray-objects
- typedArrayConstructor('Uint8', 1, function (init) {
- return function Uint8Array(data, byteOffset, length) {
- return init(this, data, byteOffset, length);
- };
- });
- },{"../internals/typed-array-constructor":163}],234:[function(require,module,exports){
- var typedArrayConstructor = require('../internals/typed-array-constructor');
- // `Uint8ClampedArray` constructor
- // https://tc39.github.io/ecma262/#sec-typedarray-objects
- typedArrayConstructor('Uint8', 1, function (init) {
- return function Uint8ClampedArray(data, byteOffset, length) {
- return init(this, data, byteOffset, length);
- };
- }, true);
- },{"../internals/typed-array-constructor":163}],235:[function(require,module,exports){
- var global = require('../internals/global');
- var DOMIterables = require('../internals/dom-iterables');
- var forEach = require('../internals/array-for-each');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- for (var COLLECTION_NAME in DOMIterables) {
- var Collection = global[COLLECTION_NAME];
- var CollectionPrototype = Collection && Collection.prototype;
- // some Chrome versions have non-configurable methods on DOMTokenList
- if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try {
- createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach);
- } catch (error) {
- CollectionPrototype.forEach = forEach;
- }
- }
- },{"../internals/array-for-each":60,"../internals/create-non-enumerable-property":76,"../internals/dom-iterables":83,"../internals/global":92}],236:[function(require,module,exports){
- var global = require('../internals/global');
- var DOMIterables = require('../internals/dom-iterables');
- var ArrayIteratorMethods = require('../modules/es.array.iterator');
- var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
- var wellKnownSymbol = require('../internals/well-known-symbol');
- var ITERATOR = wellKnownSymbol('iterator');
- var TO_STRING_TAG = wellKnownSymbol('toStringTag');
- var ArrayValues = ArrayIteratorMethods.values;
- for (var COLLECTION_NAME in DOMIterables) {
- var Collection = global[COLLECTION_NAME];
- var CollectionPrototype = Collection && Collection.prototype;
- if (CollectionPrototype) {
- // some Chrome versions have non-configurable methods on DOMTokenList
- if (CollectionPrototype[ITERATOR] !== ArrayValues) try {
- createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues);
- } catch (error) {
- CollectionPrototype[ITERATOR] = ArrayValues;
- }
- if (!CollectionPrototype[TO_STRING_TAG]) {
- createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);
- }
- if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) {
- // some Chrome versions have non-configurable methods on DOMTokenList
- if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {
- createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);
- } catch (error) {
- CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];
- }
- }
- }
- }
- },{"../internals/create-non-enumerable-property":76,"../internals/dom-iterables":83,"../internals/global":92,"../internals/well-known-symbol":169,"../modules/es.array.iterator":182}],237:[function(require,module,exports){
- var $ = require('../internals/export');
- var global = require('../internals/global');
- var userAgent = require('../internals/user-agent');
- var slice = [].slice;
- var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check
- var wrap = function (scheduler) {
- return function (handler, timeout /* , ...arguments */) {
- var boundArgs = arguments.length > 2;
- var args = boundArgs ? slice.call(arguments, 2) : undefined;
- return scheduler(boundArgs ? function () {
- // eslint-disable-next-line no-new-func
- (typeof handler == 'function' ? handler : Function(handler)).apply(this, args);
- } : handler, timeout);
- };
- };
- // ie9- setTimeout & setInterval additional parameters fix
- // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
- $({ global: true, bind: true, forced: MSIE }, {
- // `setTimeout` method
- // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
- setTimeout: wrap(global.setTimeout),
- // `setInterval` method
- // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
- setInterval: wrap(global.setInterval)
- });
- },{"../internals/export":85,"../internals/global":92,"../internals/user-agent":167}],238:[function(require,module,exports){
- (function (Buffer){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // NOTE: These type checking functions intentionally don't use `instanceof`
- // because it is fragile and can be easily faked with `Object.create()`.
- function isArray(arg) {
- if (Array.isArray) {
- return Array.isArray(arg);
- }
- return objectToString(arg) === '[object Array]';
- }
- exports.isArray = isArray;
- function isBoolean(arg) {
- return typeof arg === 'boolean';
- }
- exports.isBoolean = isBoolean;
- function isNull(arg) {
- return arg === null;
- }
- exports.isNull = isNull;
- function isNullOrUndefined(arg) {
- return arg == null;
- }
- exports.isNullOrUndefined = isNullOrUndefined;
- function isNumber(arg) {
- return typeof arg === 'number';
- }
- exports.isNumber = isNumber;
- function isString(arg) {
- return typeof arg === 'string';
- }
- exports.isString = isString;
- function isSymbol(arg) {
- return typeof arg === 'symbol';
- }
- exports.isSymbol = isSymbol;
- function isUndefined(arg) {
- return arg === void 0;
- }
- exports.isUndefined = isUndefined;
- function isRegExp(re) {
- return objectToString(re) === '[object RegExp]';
- }
- exports.isRegExp = isRegExp;
- function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
- }
- exports.isObject = isObject;
- function isDate(d) {
- return objectToString(d) === '[object Date]';
- }
- exports.isDate = isDate;
- function isError(e) {
- return (objectToString(e) === '[object Error]' || e instanceof Error);
- }
- exports.isError = isError;
- function isFunction(arg) {
- return typeof arg === 'function';
- }
- exports.isFunction = isFunction;
- function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
- }
- exports.isPrimitive = isPrimitive;
- exports.isBuffer = Buffer.isBuffer;
- function objectToString(o) {
- return Object.prototype.toString.call(o);
- }
- }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
- },{"../../is-buffer/index.js":255}],239:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- var objectCreate = Object.create || objectCreatePolyfill
- var objectKeys = Object.keys || objectKeysPolyfill
- var bind = Function.prototype.bind || functionBindPolyfill
- function EventEmitter() {
- if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
- this._events = objectCreate(null);
- this._eventsCount = 0;
- }
- this._maxListeners = this._maxListeners || undefined;
- }
- module.exports = EventEmitter;
- // Backwards-compat with node 0.10.x
- EventEmitter.EventEmitter = EventEmitter;
- EventEmitter.prototype._events = undefined;
- EventEmitter.prototype._maxListeners = undefined;
- // By default EventEmitters will print a warning if more than 10 listeners are
- // added to it. This is a useful default which helps finding memory leaks.
- var defaultMaxListeners = 10;
- var hasDefineProperty;
- try {
- var o = {};
- if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
- hasDefineProperty = o.x === 0;
- } catch (err) { hasDefineProperty = false }
- if (hasDefineProperty) {
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
- enumerable: true,
- get: function() {
- return defaultMaxListeners;
- },
- set: function(arg) {
- // check whether the input is a positive number (whose value is zero or
- // greater and not a NaN).
- if (typeof arg !== 'number' || arg < 0 || arg !== arg)
- throw new TypeError('"defaultMaxListeners" must be a positive number');
- defaultMaxListeners = arg;
- }
- });
- } else {
- EventEmitter.defaultMaxListeners = defaultMaxListeners;
- }
- // Obviously not all Emitters should be limited to 10. This function allows
- // that to be increased. Set to zero for unlimited.
- EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
- if (typeof n !== 'number' || n < 0 || isNaN(n))
- throw new TypeError('"n" argument must be a positive number');
- this._maxListeners = n;
- return this;
- };
- function $getMaxListeners(that) {
- if (that._maxListeners === undefined)
- return EventEmitter.defaultMaxListeners;
- return that._maxListeners;
- }
- EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
- return $getMaxListeners(this);
- };
- // These standalone emit* functions are used to optimize calling of event
- // handlers for fast cases because emit() itself often has a variable number of
- // arguments and can be deoptimized because of that. These functions always have
- // the same number of arguments and thus do not get deoptimized, so the code
- // inside them can execute faster.
- function emitNone(handler, isFn, self) {
- if (isFn)
- handler.call(self);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self);
- }
- }
- function emitOne(handler, isFn, self, arg1) {
- if (isFn)
- handler.call(self, arg1);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1);
- }
- }
- function emitTwo(handler, isFn, self, arg1, arg2) {
- if (isFn)
- handler.call(self, arg1, arg2);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1, arg2);
- }
- }
- function emitThree(handler, isFn, self, arg1, arg2, arg3) {
- if (isFn)
- handler.call(self, arg1, arg2, arg3);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1, arg2, arg3);
- }
- }
- function emitMany(handler, isFn, self, args) {
- if (isFn)
- handler.apply(self, args);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].apply(self, args);
- }
- }
- EventEmitter.prototype.emit = function emit(type) {
- var er, handler, len, args, i, events;
- var doError = (type === 'error');
- events = this._events;
- if (events)
- doError = (doError && events.error == null);
- else if (!doError)
- return false;
- // If there is no 'error' event listener then throw.
- if (doError) {
- if (arguments.length > 1)
- er = arguments[1];
- if (er instanceof Error) {
- throw er; // Unhandled 'error' event
- } else {
- // At least give some kind of context to the user
- var err = new Error('Unhandled "error" event. (' + er + ')');
- err.context = er;
- throw err;
- }
- return false;
- }
- handler = events[type];
- if (!handler)
- return false;
- var isFn = typeof handler === 'function';
- len = arguments.length;
- switch (len) {
- // fast cases
- case 1:
- emitNone(handler, isFn, this);
- break;
- case 2:
- emitOne(handler, isFn, this, arguments[1]);
- break;
- case 3:
- emitTwo(handler, isFn, this, arguments[1], arguments[2]);
- break;
- case 4:
- emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
- break;
- // slower
- default:
- args = new Array(len - 1);
- for (i = 1; i < len; i++)
- args[i - 1] = arguments[i];
- emitMany(handler, isFn, this, args);
- }
- return true;
- };
- function _addListener(target, type, listener, prepend) {
- var m;
- var events;
- var existing;
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
- events = target._events;
- if (!events) {
- events = target._events = objectCreate(null);
- target._eventsCount = 0;
- } else {
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (events.newListener) {
- target.emit('newListener', type,
- listener.listener ? listener.listener : listener);
- // Re-assign `events` because a newListener handler could have caused the
- // this._events to be assigned to a new object
- events = target._events;
- }
- existing = events[type];
- }
- if (!existing) {
- // Optimize the case of one listener. Don't need the extra array object.
- existing = events[type] = listener;
- ++target._eventsCount;
- } else {
- if (typeof existing === 'function') {
- // Adding the second element, need to change to array.
- existing = events[type] =
- prepend ? [listener, existing] : [existing, listener];
- } else {
- // If we've already got an array, just append.
- if (prepend) {
- existing.unshift(listener);
- } else {
- existing.push(listener);
- }
- }
- // Check for listener leak
- if (!existing.warned) {
- m = $getMaxListeners(target);
- if (m && m > 0 && existing.length > m) {
- existing.warned = true;
- var w = new Error('Possible EventEmitter memory leak detected. ' +
- existing.length + ' "' + String(type) + '" listeners ' +
- 'added. Use emitter.setMaxListeners() to ' +
- 'increase limit.');
- w.name = 'MaxListenersExceededWarning';
- w.emitter = target;
- w.type = type;
- w.count = existing.length;
- if (typeof console === 'object' && console.warn) {
- console.warn('%s: %s', w.name, w.message);
- }
- }
- }
- }
- return target;
- }
- EventEmitter.prototype.addListener = function addListener(type, listener) {
- return _addListener(this, type, listener, false);
- };
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
- EventEmitter.prototype.prependListener =
- function prependListener(type, listener) {
- return _addListener(this, type, listener, true);
- };
- function onceWrapper() {
- if (!this.fired) {
- this.target.removeListener(this.type, this.wrapFn);
- this.fired = true;
- switch (arguments.length) {
- case 0:
- return this.listener.call(this.target);
- case 1:
- return this.listener.call(this.target, arguments[0]);
- case 2:
- return this.listener.call(this.target, arguments[0], arguments[1]);
- case 3:
- return this.listener.call(this.target, arguments[0], arguments[1],
- arguments[2]);
- default:
- var args = new Array(arguments.length);
- for (var i = 0; i < args.length; ++i)
- args[i] = arguments[i];
- this.listener.apply(this.target, args);
- }
- }
- }
- function _onceWrap(target, type, listener) {
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
- var wrapped = bind.call(onceWrapper, state);
- wrapped.listener = listener;
- state.wrapFn = wrapped;
- return wrapped;
- }
- EventEmitter.prototype.once = function once(type, listener) {
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
- this.on(type, _onceWrap(this, type, listener));
- return this;
- };
- EventEmitter.prototype.prependOnceListener =
- function prependOnceListener(type, listener) {
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
- this.prependListener(type, _onceWrap(this, type, listener));
- return this;
- };
- // Emits a 'removeListener' event if and only if the listener was removed.
- EventEmitter.prototype.removeListener =
- function removeListener(type, listener) {
- var list, events, position, i, originalListener;
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
- events = this._events;
- if (!events)
- return this;
- list = events[type];
- if (!list)
- return this;
- if (list === listener || list.listener === listener) {
- if (--this._eventsCount === 0)
- this._events = objectCreate(null);
- else {
- delete events[type];
- if (events.removeListener)
- this.emit('removeListener', type, list.listener || listener);
- }
- } else if (typeof list !== 'function') {
- position = -1;
- for (i = list.length - 1; i >= 0; i--) {
- if (list[i] === listener || list[i].listener === listener) {
- originalListener = list[i].listener;
- position = i;
- break;
- }
- }
- if (position < 0)
- return this;
- if (position === 0)
- list.shift();
- else
- spliceOne(list, position);
- if (list.length === 1)
- events[type] = list[0];
- if (events.removeListener)
- this.emit('removeListener', type, originalListener || listener);
- }
- return this;
- };
- EventEmitter.prototype.removeAllListeners =
- function removeAllListeners(type) {
- var listeners, events, i;
- events = this._events;
- if (!events)
- return this;
- // not listening for removeListener, no need to emit
- if (!events.removeListener) {
- if (arguments.length === 0) {
- this._events = objectCreate(null);
- this._eventsCount = 0;
- } else if (events[type]) {
- if (--this._eventsCount === 0)
- this._events = objectCreate(null);
- else
- delete events[type];
- }
- return this;
- }
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- var keys = objectKeys(events);
- var key;
- for (i = 0; i < keys.length; ++i) {
- key = keys[i];
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
- }
- this.removeAllListeners('removeListener');
- this._events = objectCreate(null);
- this._eventsCount = 0;
- return this;
- }
- listeners = events[type];
- if (typeof listeners === 'function') {
- this.removeListener(type, listeners);
- } else if (listeners) {
- // LIFO order
- for (i = listeners.length - 1; i >= 0; i--) {
- this.removeListener(type, listeners[i]);
- }
- }
- return this;
- };
- function _listeners(target, type, unwrap) {
- var events = target._events;
- if (!events)
- return [];
- var evlistener = events[type];
- if (!evlistener)
- return [];
- if (typeof evlistener === 'function')
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
- return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
- }
- EventEmitter.prototype.listeners = function listeners(type) {
- return _listeners(this, type, true);
- };
- EventEmitter.prototype.rawListeners = function rawListeners(type) {
- return _listeners(this, type, false);
- };
- EventEmitter.listenerCount = function(emitter, type) {
- if (typeof emitter.listenerCount === 'function') {
- return emitter.listenerCount(type);
- } else {
- return listenerCount.call(emitter, type);
- }
- };
- EventEmitter.prototype.listenerCount = listenerCount;
- function listenerCount(type) {
- var events = this._events;
- if (events) {
- var evlistener = events[type];
- if (typeof evlistener === 'function') {
- return 1;
- } else if (evlistener) {
- return evlistener.length;
- }
- }
- return 0;
- }
- EventEmitter.prototype.eventNames = function eventNames() {
- return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
- };
- // About 1.5x faster than the two-arg version of Array#splice().
- function spliceOne(list, index) {
- for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
- list[i] = list[k];
- list.pop();
- }
- function arrayClone(arr, n) {
- var copy = new Array(n);
- for (var i = 0; i < n; ++i)
- copy[i] = arr[i];
- return copy;
- }
- function unwrapListeners(arr) {
- var ret = new Array(arr.length);
- for (var i = 0; i < ret.length; ++i) {
- ret[i] = arr[i].listener || arr[i];
- }
- return ret;
- }
- function objectCreatePolyfill(proto) {
- var F = function() {};
- F.prototype = proto;
- return new F;
- }
- function objectKeysPolyfill(obj) {
- var keys = [];
- for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
- keys.push(k);
- }
- return k;
- }
- function functionBindPolyfill(context) {
- var fn = this;
- return function () {
- return fn.apply(context, arguments);
- };
- }
- },{}],240:[function(require,module,exports){
- var Parser = require('./lib/parser');
- function getGlobal() {
- return (1,eval)('this');
- }
- module.exports = {
- create: function(buffer, global) {
- global = global || getGlobal();
- if(buffer instanceof global.ArrayBuffer) {
- var DOMBufferStream = require('./lib/dom-bufferstream');
- return new Parser(new DOMBufferStream(buffer, 0, buffer.byteLength, true, global));
- } else {
- var NodeBufferStream = require('./lib/bufferstream');
- return new Parser(new NodeBufferStream(buffer, 0, buffer.length, true));
- }
- }
- };
- },{"./lib/bufferstream":241,"./lib/dom-bufferstream":243,"./lib/parser":247}],241:[function(require,module,exports){
- function BufferStream(buffer, offset, length, bigEndian) {
- this.buffer = buffer;
- this.offset = offset || 0;
- length = typeof length === 'number' ? length : buffer.length;
- this.endPosition = this.offset + length;
- this.setBigEndian(bigEndian);
- }
- BufferStream.prototype = {
- setBigEndian: function(bigEndian) {
- this.bigEndian = !!bigEndian;
- },
- nextUInt8: function() {
- var value = this.buffer.readUInt8(this.offset);
- this.offset += 1;
- return value;
- },
- nextInt8: function() {
- var value = this.buffer.readInt8(this.offset);
- this.offset += 1;
- return value;
- },
- nextUInt16: function() {
- var value = this.bigEndian ? this.buffer.readUInt16BE(this.offset) : this.buffer.readUInt16LE(this.offset);
- this.offset += 2;
- return value;
- },
- nextUInt32: function() {
- var value = this.bigEndian ? this.buffer.readUInt32BE(this.offset) : this.buffer.readUInt32LE(this.offset);
- this.offset += 4;
- return value;
- },
- nextInt16: function() {
- var value = this.bigEndian ? this.buffer.readInt16BE(this.offset) : this.buffer.readInt16LE(this.offset);
- this.offset += 2;
- return value;
- },
- nextInt32: function() {
- var value = this.bigEndian ? this.buffer.readInt32BE(this.offset) : this.buffer.readInt32LE(this.offset);
- this.offset += 4;
- return value;
- },
- nextFloat: function() {
- var value = this.bigEndian ? this.buffer.readFloatBE(this.offset) : this.buffer.readFloatLE(this.offset);
- this.offset += 4;
- return value;
- },
- nextDouble: function() {
- var value = this.bigEndian ? this.buffer.readDoubleBE(this.offset) : this.buffer.readDoubleLE(this.offset);
- this.offset += 8;
- return value;
- },
- nextBuffer: function(length) {
- var value = this.buffer.slice(this.offset, this.offset + length);
- this.offset += length;
- return value;
- },
- remainingLength: function() {
- return this.endPosition - this.offset;
- },
- nextString: function(length) {
- var value = this.buffer.toString('utf8', this.offset, this.offset + length);
- this.offset += length;
- return value;
- },
- mark: function() {
- var self = this;
- return {
- openWithOffset: function(offset) {
- offset = (offset || 0) + this.offset;
- return new BufferStream(self.buffer, offset, self.endPosition - offset, self.bigEndian);
- },
- offset: this.offset
- };
- },
- offsetFrom: function(marker) {
- return this.offset - marker.offset;
- },
- skip: function(amount) {
- this.offset += amount;
- },
- branch: function(offset, length) {
- length = typeof length === 'number' ? length : this.endPosition - (this.offset + offset);
- return new BufferStream(this.buffer, this.offset + offset, length, this.bigEndian);
- }
- };
- module.exports = BufferStream;
- },{}],242:[function(require,module,exports){
- function parseNumber(s) {
- return parseInt(s, 10);
- }
- //in seconds
- var hours = 3600;
- var minutes = 60;
- //take date (year, month, day) and time (hour, minutes, seconds) digits in UTC
- //and return a timestamp in seconds
- function parseDateTimeParts(dateParts, timeParts) {
- dateParts = dateParts.map(parseNumber);
- timeParts = timeParts.map(parseNumber);
- var year = dateParts[0];
- var month = dateParts[1] - 1;
- var day = dateParts[2];
- var hours = timeParts[0];
- var minutes = timeParts[1];
- var seconds = timeParts[2];
- var date = Date.UTC(year, month, day, hours, minutes, seconds, 0);
- var timestamp = date / 1000;
- return timestamp;
- }
- //parse date with "2004-09-04T23:39:06-08:00" format,
- //one of the formats supported by ISO 8601, and
- //convert to utc timestamp in seconds
- function parseDateWithTimezoneFormat(dateTimeStr) {
- var dateParts = dateTimeStr.substr(0, 10).split('-');
- var timeParts = dateTimeStr.substr(11, 8).split(':');
- var timezoneStr = dateTimeStr.substr(19, 6);
- var timezoneParts = timezoneStr.split(':').map(parseNumber);
- var timezoneOffset = (timezoneParts[0] * hours) +
- (timezoneParts[1] * minutes);
- var timestamp = parseDateTimeParts(dateParts, timeParts);
- //minus because the timezoneOffset describes
- //how much the described time is ahead of UTC
- timestamp -= timezoneOffset;
- if(typeof timestamp === 'number' && !isNaN(timestamp)) {
- return timestamp;
- }
- }
- //parse date with "YYYY:MM:DD hh:mm:ss" format, convert to utc timestamp in seconds
- function parseDateWithSpecFormat(dateTimeStr) {
- var parts = dateTimeStr.split(' '),
- dateParts = parts[0].split(':'),
- timeParts = parts[1].split(':');
- var timestamp = parseDateTimeParts(dateParts, timeParts);
- if(typeof timestamp === 'number' && !isNaN(timestamp)) {
- return timestamp;
- }
- }
- function parseExifDate(dateTimeStr) {
- //some easy checks to determine two common date formats
- //is the date in the standard "YYYY:MM:DD hh:mm:ss" format?
- var isSpecFormat = dateTimeStr.length === 19 &&
- dateTimeStr.charAt(4) === ':';
- //is the date in the non-standard format,
- //"2004-09-04T23:39:06-08:00" to include a timezone?
- var isTimezoneFormat = dateTimeStr.length === 25 &&
- dateTimeStr.charAt(10) === 'T';
- var timestamp;
- if(isTimezoneFormat) {
- return parseDateWithTimezoneFormat(dateTimeStr);
- }
- else if(isSpecFormat) {
- return parseDateWithSpecFormat(dateTimeStr);
- }
- }
- module.exports = {
- parseDateWithSpecFormat: parseDateWithSpecFormat,
- parseDateWithTimezoneFormat: parseDateWithTimezoneFormat,
- parseExifDate: parseExifDate
- };
- },{}],243:[function(require,module,exports){
- /*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */
- function DOMBufferStream(arrayBuffer, offset, length, bigEndian, global, parentOffset) {
- this.global = global;
- offset = offset || 0;
- length = length || (arrayBuffer.byteLength - offset);
- this.arrayBuffer = arrayBuffer.slice(offset, offset + length);
- this.view = new global.DataView(this.arrayBuffer, 0, this.arrayBuffer.byteLength);
- this.setBigEndian(bigEndian);
- this.offset = 0;
- this.parentOffset = (parentOffset || 0) + offset;
- }
- DOMBufferStream.prototype = {
- setBigEndian: function(bigEndian) {
- this.littleEndian = !bigEndian;
- },
- nextUInt8: function() {
- var value = this.view.getUint8(this.offset);
- this.offset += 1;
- return value;
- },
- nextInt8: function() {
- var value = this.view.getInt8(this.offset);
- this.offset += 1;
- return value;
- },
- nextUInt16: function() {
- var value = this.view.getUint16(this.offset, this.littleEndian);
- this.offset += 2;
- return value;
- },
- nextUInt32: function() {
- var value = this.view.getUint32(this.offset, this.littleEndian);
- this.offset += 4;
- return value;
- },
- nextInt16: function() {
- var value = this.view.getInt16(this.offset, this.littleEndian);
- this.offset += 2;
- return value;
- },
- nextInt32: function() {
- var value = this.view.getInt32(this.offset, this.littleEndian);
- this.offset += 4;
- return value;
- },
- nextFloat: function() {
- var value = this.view.getFloat32(this.offset, this.littleEndian);
- this.offset += 4;
- return value;
- },
- nextDouble: function() {
- var value = this.view.getFloat64(this.offset, this.littleEndian);
- this.offset += 8;
- return value;
- },
- nextBuffer: function(length) {
- //this won't work in IE10
- var value = this.arrayBuffer.slice(this.offset, this.offset + length);
- this.offset += length;
- return value;
- },
- remainingLength: function() {
- return this.arrayBuffer.byteLength - this.offset;
- },
- nextString: function(length) {
- var value = this.arrayBuffer.slice(this.offset, this.offset + length);
- value = String.fromCharCode.apply(null, new this.global.Uint8Array(value));
- this.offset += length;
- return value;
- },
- mark: function() {
- var self = this;
- return {
- openWithOffset: function(offset) {
- offset = (offset || 0) + this.offset;
- return new DOMBufferStream(self.arrayBuffer, offset, self.arrayBuffer.byteLength - offset, !self.littleEndian, self.global, self.parentOffset);
- },
- offset: this.offset,
- getParentOffset: function() {
- return self.parentOffset;
- }
- };
- },
- offsetFrom: function(marker) {
- return this.parentOffset + this.offset - (marker.offset + marker.getParentOffset());
- },
- skip: function(amount) {
- this.offset += amount;
- },
- branch: function(offset, length) {
- length = typeof length === 'number' ? length : this.arrayBuffer.byteLength - (this.offset + offset);
- return new DOMBufferStream(this.arrayBuffer, this.offset + offset, length, !this.littleEndian, this.global, this.parentOffset);
- }
- };
- module.exports = DOMBufferStream;
- },{}],244:[function(require,module,exports){
- module.exports = {
- exif : {
- 0x0001 : "InteropIndex",
- 0x0002 : "InteropVersion",
- 0x000B : "ProcessingSoftware",
- 0x00FE : "SubfileType",
- 0x00FF : "OldSubfileType",
- 0x0100 : "ImageWidth",
- 0x0101 : "ImageHeight",
- 0x0102 : "BitsPerSample",
- 0x0103 : "Compression",
- 0x0106 : "PhotometricInterpretation",
- 0x0107 : "Thresholding",
- 0x0108 : "CellWidth",
- 0x0109 : "CellLength",
- 0x010A : "FillOrder",
- 0x010D : "DocumentName",
- 0x010E : "ImageDescription",
- 0x010F : "Make",
- 0x0110 : "Model",
- 0x0111 : "StripOffsets",
- 0x0112 : "Orientation",
- 0x0115 : "SamplesPerPixel",
- 0x0116 : "RowsPerStrip",
- 0x0117 : "StripByteCounts",
- 0x0118 : "MinSampleValue",
- 0x0119 : "MaxSampleValue",
- 0x011A : "XResolution",
- 0x011B : "YResolution",
- 0x011C : "PlanarConfiguration",
- 0x011D : "PageName",
- 0x011E : "XPosition",
- 0x011F : "YPosition",
- 0x0120 : "FreeOffsets",
- 0x0121 : "FreeByteCounts",
- 0x0122 : "GrayResponseUnit",
- 0x0123 : "GrayResponseCurve",
- 0x0124 : "T4Options",
- 0x0125 : "T6Options",
- 0x0128 : "ResolutionUnit",
- 0x0129 : "PageNumber",
- 0x012C : "ColorResponseUnit",
- 0x012D : "TransferFunction",
- 0x0131 : "Software",
- 0x0132 : "ModifyDate",
- 0x013B : "Artist",
- 0x013C : "HostComputer",
- 0x013D : "Predictor",
- 0x013E : "WhitePoint",
- 0x013F : "PrimaryChromaticities",
- 0x0140 : "ColorMap",
- 0x0141 : "HalftoneHints",
- 0x0142 : "TileWidth",
- 0x0143 : "TileLength",
- 0x0144 : "TileOffsets",
- 0x0145 : "TileByteCounts",
- 0x0146 : "BadFaxLines",
- 0x0147 : "CleanFaxData",
- 0x0148 : "ConsecutiveBadFaxLines",
- 0x014A : "SubIFD",
- 0x014C : "InkSet",
- 0x014D : "InkNames",
- 0x014E : "NumberofInks",
- 0x0150 : "DotRange",
- 0x0151 : "TargetPrinter",
- 0x0152 : "ExtraSamples",
- 0x0153 : "SampleFormat",
- 0x0154 : "SMinSampleValue",
- 0x0155 : "SMaxSampleValue",
- 0x0156 : "TransferRange",
- 0x0157 : "ClipPath",
- 0x0158 : "XClipPathUnits",
- 0x0159 : "YClipPathUnits",
- 0x015A : "Indexed",
- 0x015B : "JPEGTables",
- 0x015F : "OPIProxy",
- 0x0190 : "GlobalParametersIFD",
- 0x0191 : "ProfileType",
- 0x0192 : "FaxProfile",
- 0x0193 : "CodingMethods",
- 0x0194 : "VersionYear",
- 0x0195 : "ModeNumber",
- 0x01B1 : "Decode",
- 0x01B2 : "DefaultImageColor",
- 0x01B3 : "T82Options",
- 0x01B5 : "JPEGTables",
- 0x0200 : "JPEGProc",
- 0x0201 : "ThumbnailOffset",
- 0x0202 : "ThumbnailLength",
- 0x0203 : "JPEGRestartInterval",
- 0x0205 : "JPEGLosslessPredictors",
- 0x0206 : "JPEGPointTransforms",
- 0x0207 : "JPEGQTables",
- 0x0208 : "JPEGDCTables",
- 0x0209 : "JPEGACTables",
- 0x0211 : "YCbCrCoefficients",
- 0x0212 : "YCbCrSubSampling",
- 0x0213 : "YCbCrPositioning",
- 0x0214 : "ReferenceBlackWhite",
- 0x022F : "StripRowCounts",
- 0x02BC : "ApplicationNotes",
- 0x03E7 : "USPTOMiscellaneous",
- 0x1000 : "RelatedImageFileFormat",
- 0x1001 : "RelatedImageWidth",
- 0x1002 : "RelatedImageHeight",
- 0x4746 : "Rating",
- 0x4747 : "XP_DIP_XML",
- 0x4748 : "StitchInfo",
- 0x4749 : "RatingPercent",
- 0x800D : "ImageID",
- 0x80A3 : "WangTag1",
- 0x80A4 : "WangAnnotation",
- 0x80A5 : "WangTag3",
- 0x80A6 : "WangTag4",
- 0x80E3 : "Matteing",
- 0x80E4 : "DataType",
- 0x80E5 : "ImageDepth",
- 0x80E6 : "TileDepth",
- 0x827D : "Model2",
- 0x828D : "CFARepeatPatternDim",
- 0x828E : "CFAPattern2",
- 0x828F : "BatteryLevel",
- 0x8290 : "KodakIFD",
- 0x8298 : "Copyright",
- 0x829A : "ExposureTime",
- 0x829D : "FNumber",
- 0x82A5 : "MDFileTag",
- 0x82A6 : "MDScalePixel",
- 0x82A7 : "MDColorTable",
- 0x82A8 : "MDLabName",
- 0x82A9 : "MDSampleInfo",
- 0x82AA : "MDPrepDate",
- 0x82AB : "MDPrepTime",
- 0x82AC : "MDFileUnits",
- 0x830E : "PixelScale",
- 0x8335 : "AdventScale",
- 0x8336 : "AdventRevision",
- 0x835C : "UIC1Tag",
- 0x835D : "UIC2Tag",
- 0x835E : "UIC3Tag",
- 0x835F : "UIC4Tag",
- 0x83BB : "IPTC-NAA",
- 0x847E : "IntergraphPacketData",
- 0x847F : "IntergraphFlagRegisters",
- 0x8480 : "IntergraphMatrix",
- 0x8481 : "INGRReserved",
- 0x8482 : "ModelTiePoint",
- 0x84E0 : "Site",
- 0x84E1 : "ColorSequence",
- 0x84E2 : "IT8Header",
- 0x84E3 : "RasterPadding",
- 0x84E4 : "BitsPerRunLength",
- 0x84E5 : "BitsPerExtendedRunLength",
- 0x84E6 : "ColorTable",
- 0x84E7 : "ImageColorIndicator",
- 0x84E8 : "BackgroundColorIndicator",
- 0x84E9 : "ImageColorValue",
- 0x84EA : "BackgroundColorValue",
- 0x84EB : "PixelIntensityRange",
- 0x84EC : "TransparencyIndicator",
- 0x84ED : "ColorCharacterization",
- 0x84EE : "HCUsage",
- 0x84EF : "TrapIndicator",
- 0x84F0 : "CMYKEquivalent",
- 0x8546 : "SEMInfo",
- 0x8568 : "AFCP_IPTC",
- 0x85B8 : "PixelMagicJBIGOptions",
- 0x85D8 : "ModelTransform",
- 0x8602 : "WB_GRGBLevels",
- 0x8606 : "LeafData",
- 0x8649 : "PhotoshopSettings",
- 0x8769 : "ExifOffset",
- 0x8773 : "ICC_Profile",
- 0x877F : "TIFF_FXExtensions",
- 0x8780 : "MultiProfiles",
- 0x8781 : "SharedData",
- 0x8782 : "T88Options",
- 0x87AC : "ImageLayer",
- 0x87AF : "GeoTiffDirectory",
- 0x87B0 : "GeoTiffDoubleParams",
- 0x87B1 : "GeoTiffAsciiParams",
- 0x8822 : "ExposureProgram",
- 0x8824 : "SpectralSensitivity",
- 0x8825 : "GPSInfo",
- 0x8827 : "ISO",
- 0x8828 : "Opto-ElectricConvFactor",
- 0x8829 : "Interlace",
- 0x882A : "TimeZoneOffset",
- 0x882B : "SelfTimerMode",
- 0x8830 : "SensitivityType",
- 0x8831 : "StandardOutputSensitivity",
- 0x8832 : "RecommendedExposureIndex",
- 0x8833 : "ISOSpeed",
- 0x8834 : "ISOSpeedLatitudeyyy",
- 0x8835 : "ISOSpeedLatitudezzz",
- 0x885C : "FaxRecvParams",
- 0x885D : "FaxSubAddress",
- 0x885E : "FaxRecvTime",
- 0x888A : "LeafSubIFD",
- 0x9000 : "ExifVersion",
- 0x9003 : "DateTimeOriginal",
- 0x9004 : "CreateDate",
- 0x9101 : "ComponentsConfiguration",
- 0x9102 : "CompressedBitsPerPixel",
- 0x9201 : "ShutterSpeedValue",
- 0x9202 : "ApertureValue",
- 0x9203 : "BrightnessValue",
- 0x9204 : "ExposureCompensation",
- 0x9205 : "MaxApertureValue",
- 0x9206 : "SubjectDistance",
- 0x9207 : "MeteringMode",
- 0x9208 : "LightSource",
- 0x9209 : "Flash",
- 0x920A : "FocalLength",
- 0x920B : "FlashEnergy",
- 0x920C : "SpatialFrequencyResponse",
- 0x920D : "Noise",
- 0x920E : "FocalPlaneXResolution",
- 0x920F : "FocalPlaneYResolution",
- 0x9210 : "FocalPlaneResolutionUnit",
- 0x9211 : "ImageNumber",
- 0x9212 : "SecurityClassification",
- 0x9213 : "ImageHistory",
- 0x9214 : "SubjectArea",
- 0x9215 : "ExposureIndex",
- 0x9216 : "TIFF-EPStandardID",
- 0x9217 : "SensingMethod",
- 0x923A : "CIP3DataFile",
- 0x923B : "CIP3Sheet",
- 0x923C : "CIP3Side",
- 0x923F : "StoNits",
- 0x927C : "MakerNote",
- 0x9286 : "UserComment",
- 0x9290 : "SubSecTime",
- 0x9291 : "SubSecTimeOriginal",
- 0x9292 : "SubSecTimeDigitized",
- 0x932F : "MSDocumentText",
- 0x9330 : "MSPropertySetStorage",
- 0x9331 : "MSDocumentTextPosition",
- 0x935C : "ImageSourceData",
- 0x9C9B : "XPTitle",
- 0x9C9C : "XPComment",
- 0x9C9D : "XPAuthor",
- 0x9C9E : "XPKeywords",
- 0x9C9F : "XPSubject",
- 0xA000 : "FlashpixVersion",
- 0xA001 : "ColorSpace",
- 0xA002 : "ExifImageWidth",
- 0xA003 : "ExifImageHeight",
- 0xA004 : "RelatedSoundFile",
- 0xA005 : "InteropOffset",
- 0xA20B : "FlashEnergy",
- 0xA20C : "SpatialFrequencyResponse",
- 0xA20D : "Noise",
- 0xA20E : "FocalPlaneXResolution",
- 0xA20F : "FocalPlaneYResolution",
- 0xA210 : "FocalPlaneResolutionUnit",
- 0xA211 : "ImageNumber",
- 0xA212 : "SecurityClassification",
- 0xA213 : "ImageHistory",
- 0xA214 : "SubjectLocation",
- 0xA215 : "ExposureIndex",
- 0xA216 : "TIFF-EPStandardID",
- 0xA217 : "SensingMethod",
- 0xA300 : "FileSource",
- 0xA301 : "SceneType",
- 0xA302 : "CFAPattern",
- 0xA401 : "CustomRendered",
- 0xA402 : "ExposureMode",
- 0xA403 : "WhiteBalance",
- 0xA404 : "DigitalZoomRatio",
- 0xA405 : "FocalLengthIn35mmFormat",
- 0xA406 : "SceneCaptureType",
- 0xA407 : "GainControl",
- 0xA408 : "Contrast",
- 0xA409 : "Saturation",
- 0xA40A : "Sharpness",
- 0xA40B : "DeviceSettingDescription",
- 0xA40C : "SubjectDistanceRange",
- 0xA420 : "ImageUniqueID",
- 0xA430 : "OwnerName",
- 0xA431 : "SerialNumber",
- 0xA432 : "LensInfo",
- 0xA433 : "LensMake",
- 0xA434 : "LensModel",
- 0xA435 : "LensSerialNumber",
- 0xA480 : "GDALMetadata",
- 0xA481 : "GDALNoData",
- 0xA500 : "Gamma",
- 0xAFC0 : "ExpandSoftware",
- 0xAFC1 : "ExpandLens",
- 0xAFC2 : "ExpandFilm",
- 0xAFC3 : "ExpandFilterLens",
- 0xAFC4 : "ExpandScanner",
- 0xAFC5 : "ExpandFlashLamp",
- 0xBC01 : "PixelFormat",
- 0xBC02 : "Transformation",
- 0xBC03 : "Uncompressed",
- 0xBC04 : "ImageType",
- 0xBC80 : "ImageWidth",
- 0xBC81 : "ImageHeight",
- 0xBC82 : "WidthResolution",
- 0xBC83 : "HeightResolution",
- 0xBCC0 : "ImageOffset",
- 0xBCC1 : "ImageByteCount",
- 0xBCC2 : "AlphaOffset",
- 0xBCC3 : "AlphaByteCount",
- 0xBCC4 : "ImageDataDiscard",
- 0xBCC5 : "AlphaDataDiscard",
- 0xC427 : "OceScanjobDesc",
- 0xC428 : "OceApplicationSelector",
- 0xC429 : "OceIDNumber",
- 0xC42A : "OceImageLogic",
- 0xC44F : "Annotations",
- 0xC4A5 : "PrintIM",
- 0xC580 : "USPTOOriginalContentType",
- 0xC612 : "DNGVersion",
- 0xC613 : "DNGBackwardVersion",
- 0xC614 : "UniqueCameraModel",
- 0xC615 : "LocalizedCameraModel",
- 0xC616 : "CFAPlaneColor",
- 0xC617 : "CFALayout",
- 0xC618 : "LinearizationTable",
- 0xC619 : "BlackLevelRepeatDim",
- 0xC61A : "BlackLevel",
- 0xC61B : "BlackLevelDeltaH",
- 0xC61C : "BlackLevelDeltaV",
- 0xC61D : "WhiteLevel",
- 0xC61E : "DefaultScale",
- 0xC61F : "DefaultCropOrigin",
- 0xC620 : "DefaultCropSize",
- 0xC621 : "ColorMatrix1",
- 0xC622 : "ColorMatrix2",
- 0xC623 : "CameraCalibration1",
- 0xC624 : "CameraCalibration2",
- 0xC625 : "ReductionMatrix1",
- 0xC626 : "ReductionMatrix2",
- 0xC627 : "AnalogBalance",
- 0xC628 : "AsShotNeutral",
- 0xC629 : "AsShotWhiteXY",
- 0xC62A : "BaselineExposure",
- 0xC62B : "BaselineNoise",
- 0xC62C : "BaselineSharpness",
- 0xC62D : "BayerGreenSplit",
- 0xC62E : "LinearResponseLimit",
- 0xC62F : "CameraSerialNumber",
- 0xC630 : "DNGLensInfo",
- 0xC631 : "ChromaBlurRadius",
- 0xC632 : "AntiAliasStrength",
- 0xC633 : "ShadowScale",
- 0xC634 : "DNGPrivateData",
- 0xC635 : "MakerNoteSafety",
- 0xC640 : "RawImageSegmentation",
- 0xC65A : "CalibrationIlluminant1",
- 0xC65B : "CalibrationIlluminant2",
- 0xC65C : "BestQualityScale",
- 0xC65D : "RawDataUniqueID",
- 0xC660 : "AliasLayerMetadata",
- 0xC68B : "OriginalRawFileName",
- 0xC68C : "OriginalRawFileData",
- 0xC68D : "ActiveArea",
- 0xC68E : "MaskedAreas",
- 0xC68F : "AsShotICCProfile",
- 0xC690 : "AsShotPreProfileMatrix",
- 0xC691 : "CurrentICCProfile",
- 0xC692 : "CurrentPreProfileMatrix",
- 0xC6BF : "ColorimetricReference",
- 0xC6D2 : "PanasonicTitle",
- 0xC6D3 : "PanasonicTitle2",
- 0xC6F3 : "CameraCalibrationSig",
- 0xC6F4 : "ProfileCalibrationSig",
- 0xC6F5 : "ProfileIFD",
- 0xC6F6 : "AsShotProfileName",
- 0xC6F7 : "NoiseReductionApplied",
- 0xC6F8 : "ProfileName",
- 0xC6F9 : "ProfileHueSatMapDims",
- 0xC6FA : "ProfileHueSatMapData1",
- 0xC6FB : "ProfileHueSatMapData2",
- 0xC6FC : "ProfileToneCurve",
- 0xC6FD : "ProfileEmbedPolicy",
- 0xC6FE : "ProfileCopyright",
- 0xC714 : "ForwardMatrix1",
- 0xC715 : "ForwardMatrix2",
- 0xC716 : "PreviewApplicationName",
- 0xC717 : "PreviewApplicationVersion",
- 0xC718 : "PreviewSettingsName",
- 0xC719 : "PreviewSettingsDigest",
- 0xC71A : "PreviewColorSpace",
- 0xC71B : "PreviewDateTime",
- 0xC71C : "RawImageDigest",
- 0xC71D : "OriginalRawFileDigest",
- 0xC71E : "SubTileBlockSize",
- 0xC71F : "RowInterleaveFactor",
- 0xC725 : "ProfileLookTableDims",
- 0xC726 : "ProfileLookTableData",
- 0xC740 : "OpcodeList1",
- 0xC741 : "OpcodeList2",
- 0xC74E : "OpcodeList3",
- 0xC761 : "NoiseProfile",
- 0xC763 : "TimeCodes",
- 0xC764 : "FrameRate",
- 0xC772 : "TStop",
- 0xC789 : "ReelName",
- 0xC791 : "OriginalDefaultFinalSize",
- 0xC792 : "OriginalBestQualitySize",
- 0xC793 : "OriginalDefaultCropSize",
- 0xC7A1 : "CameraLabel",
- 0xC7A3 : "ProfileHueSatMapEncoding",
- 0xC7A4 : "ProfileLookTableEncoding",
- 0xC7A5 : "BaselineExposureOffset",
- 0xC7A6 : "DefaultBlackRender",
- 0xC7A7 : "NewRawImageDigest",
- 0xC7A8 : "RawToPreviewGain",
- 0xC7B5 : "DefaultUserCrop",
- 0xEA1C : "Padding",
- 0xEA1D : "OffsetSchema",
- 0xFDE8 : "OwnerName",
- 0xFDE9 : "SerialNumber",
- 0xFDEA : "Lens",
- 0xFE00 : "KDC_IFD",
- 0xFE4C : "RawFile",
- 0xFE4D : "Converter",
- 0xFE4E : "WhiteBalance",
- 0xFE51 : "Exposure",
- 0xFE52 : "Shadows",
- 0xFE53 : "Brightness",
- 0xFE54 : "Contrast",
- 0xFE55 : "Saturation",
- 0xFE56 : "Sharpness",
- 0xFE57 : "Smoothness",
- 0xFE58 : "MoireFilter"
-
- },
- gps : {
- 0x0000 : 'GPSVersionID',
- 0x0001 : 'GPSLatitudeRef',
- 0x0002 : 'GPSLatitude',
- 0x0003 : 'GPSLongitudeRef',
- 0x0004 : 'GPSLongitude',
- 0x0005 : 'GPSAltitudeRef',
- 0x0006 : 'GPSAltitude',
- 0x0007 : 'GPSTimeStamp',
- 0x0008 : 'GPSSatellites',
- 0x0009 : 'GPSStatus',
- 0x000A : 'GPSMeasureMode',
- 0x000B : 'GPSDOP',
- 0x000C : 'GPSSpeedRef',
- 0x000D : 'GPSSpeed',
- 0x000E : 'GPSTrackRef',
- 0x000F : 'GPSTrack',
- 0x0010 : 'GPSImgDirectionRef',
- 0x0011 : 'GPSImgDirection',
- 0x0012 : 'GPSMapDatum',
- 0x0013 : 'GPSDestLatitudeRef',
- 0x0014 : 'GPSDestLatitude',
- 0x0015 : 'GPSDestLongitudeRef',
- 0x0016 : 'GPSDestLongitude',
- 0x0017 : 'GPSDestBearingRef',
- 0x0018 : 'GPSDestBearing',
- 0x0019 : 'GPSDestDistanceRef',
- 0x001A : 'GPSDestDistance',
- 0x001B : 'GPSProcessingMethod',
- 0x001C : 'GPSAreaInformation',
- 0x001D : 'GPSDateStamp',
- 0x001E : 'GPSDifferential',
- 0x001F : 'GPSHPositioningError'
- }
- };
- },{}],245:[function(require,module,exports){
- /*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */
- function readExifValue(format, stream) {
- switch(format) {
- case 1: return stream.nextUInt8();
- case 3: return stream.nextUInt16();
- case 4: return stream.nextUInt32();
- case 5: return [stream.nextUInt32(), stream.nextUInt32()];
- case 6: return stream.nextInt8();
- case 8: return stream.nextUInt16();
- case 9: return stream.nextUInt32();
- case 10: return [stream.nextInt32(), stream.nextInt32()];
- case 11: return stream.nextFloat();
- case 12: return stream.nextDouble();
- default: throw new Error('Invalid format while decoding: ' + format);
- }
- }
- function getBytesPerComponent(format) {
- switch(format) {
- case 1:
- case 2:
- case 6:
- case 7:
- return 1;
- case 3:
- case 8:
- return 2;
- case 4:
- case 9:
- case 11:
- return 4;
- case 5:
- case 10:
- case 12:
- return 8;
- default:
- return 0;
- }
- }
- function readExifTag(tiffMarker, stream) {
- var tagType = stream.nextUInt16(),
- format = stream.nextUInt16(),
- bytesPerComponent = getBytesPerComponent(format),
- components = stream.nextUInt32(),
- valueBytes = bytesPerComponent * components,
- values,
- value,
- c;
- /* if the value is bigger then 4 bytes, the value is in the data section of the IFD
- and the value present in the tag is the offset starting from the tiff header. So we replace the stream
- with a stream that is located at the given offset in the data section. s*/
- if(valueBytes > 4) {
- stream = tiffMarker.openWithOffset(stream.nextUInt32());
- }
- //we don't want to read strings as arrays
- if(format === 2) {
- values = stream.nextString(components);
- //cut off \0 characters
- var lastNull = values.indexOf('\0');
- if(lastNull !== -1) {
- values = values.substr(0, lastNull);
- }
- }
- else if(format === 7) {
- values = stream.nextBuffer(components);
- }
- else if(format !== 0) {
- values = [];
- for(c = 0; c < components; ++c) {
- values.push(readExifValue(format, stream));
- }
- }
- //since our stream is a stateful object, we need to skip remaining bytes
- //so our offset stays correct
- if(valueBytes < 4) {
- stream.skip(4 - valueBytes);
- }
- return [tagType, values, format];
- }
- function readIFDSection(tiffMarker, stream, iterator) {
- var numberOfEntries = stream.nextUInt16(), tag, i;
- for(i = 0; i < numberOfEntries; ++i) {
- tag = readExifTag(tiffMarker, stream);
- iterator(tag[0], tag[1], tag[2]);
- }
- }
- function readHeader(stream) {
- var exifHeader = stream.nextString(6);
- if(exifHeader !== 'Exif\0\0') {
- throw new Error('Invalid EXIF header');
- }
- var tiffMarker = stream.mark();
- var tiffHeader = stream.nextUInt16();
- if(tiffHeader === 0x4949) {
- stream.setBigEndian(false);
- } else if(tiffHeader === 0x4D4D) {
- stream.setBigEndian(true);
- } else {
- throw new Error('Invalid TIFF header');
- }
- if(stream.nextUInt16() !== 0x002A) {
- throw new Error('Invalid TIFF data');
- }
- return tiffMarker;
- }
- module.exports = {
- IFD0: 1,
- IFD1: 2,
- GPSIFD: 3,
- SubIFD: 4,
- InteropIFD: 5,
- parseTags: function(stream, iterator) {
- var tiffMarker;
- try {
- tiffMarker = readHeader(stream);
- } catch(e) {
- return false; //ignore APP1 sections with invalid headers
- }
- var subIfdOffset, gpsOffset, interopOffset;
- var ifd0Stream = tiffMarker.openWithOffset(stream.nextUInt32()),
- IFD0 = this.IFD0;
- readIFDSection(tiffMarker, ifd0Stream, function(tagType, value, format) {
- switch(tagType) {
- case 0x8825: gpsOffset = value[0]; break;
- case 0x8769: subIfdOffset = value[0]; break;
- default: iterator(IFD0, tagType, value, format); break;
- }
- });
- var ifd1Offset = ifd0Stream.nextUInt32();
- if(ifd1Offset !== 0) {
- var ifd1Stream = tiffMarker.openWithOffset(ifd1Offset);
- readIFDSection(tiffMarker, ifd1Stream, iterator.bind(null, this.IFD1));
- }
- if(gpsOffset) {
- var gpsStream = tiffMarker.openWithOffset(gpsOffset);
- readIFDSection(tiffMarker, gpsStream, iterator.bind(null, this.GPSIFD));
- }
- if(subIfdOffset) {
- var subIfdStream = tiffMarker.openWithOffset(subIfdOffset), InteropIFD = this.InteropIFD;
- readIFDSection(tiffMarker, subIfdStream, function(tagType, value, format) {
- if(tagType === 0xA005) {
- interopOffset = value[0];
- } else {
- iterator(InteropIFD, tagType, value, format);
- }
- });
- }
- if(interopOffset) {
- var interopStream = tiffMarker.openWithOffset(interopOffset);
- readIFDSection(tiffMarker, interopStream, iterator.bind(null, this.InteropIFD));
- }
- return true;
- }
- };
- },{}],246:[function(require,module,exports){
- /*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */
- module.exports = {
- parseSections: function(stream, iterator) {
- var len, markerType;
- stream.setBigEndian(true);
- //stop reading the stream at the SOS (Start of Stream) marker,
- //because its length is not stored in the header so we can't
- //know where to jump to. The only marker after that is just EOI (End Of Image) anyway
- while(stream.remainingLength() > 0 && markerType !== 0xDA) {
- if(stream.nextUInt8() !== 0xFF) {
- throw new Error('Invalid JPEG section offset');
- }
- markerType = stream.nextUInt8();
- //don't read size from markers that have no datas
- if((markerType >= 0xD0 && markerType <= 0xD9) || markerType === 0xDA) {
- len = 0;
- } else {
- len = stream.nextUInt16() - 2;
- }
- iterator(markerType, stream.branch(0, len));
- stream.skip(len);
- }
- },
- //stream should be located after SOF section size and in big endian mode, like passed to parseSections iterator
- getSizeFromSOFSection: function(stream) {
- stream.skip(1);
- return {
- height: stream.nextUInt16(),
- width: stream.nextUInt16()
- };
- },
- getSectionName: function(markerType) {
- var name, index;
- switch(markerType) {
- case 0xD8: name = 'SOI'; break;
- case 0xC4: name = 'DHT'; break;
- case 0xDB: name = 'DQT'; break;
- case 0xDD: name = 'DRI'; break;
- case 0xDA: name = 'SOS'; break;
- case 0xFE: name = 'COM'; break;
- case 0xD9: name = 'EOI'; break;
- default:
- if(markerType >= 0xE0 && markerType <= 0xEF) {
- name = 'APP';
- index = markerType - 0xE0;
- }
- else if(markerType >= 0xC0 && markerType <= 0xCF && markerType !== 0xC4 && markerType !== 0xC8 && markerType !== 0xCC) {
- name = 'SOF';
- index = markerType - 0xC0;
- }
- else if(markerType >= 0xD0 && markerType <= 0xD7) {
- name = 'RST';
- index = markerType - 0xD0;
- }
- break;
- }
- var nameStruct = {
- name: name
- };
- if(typeof index === 'number') {
- nameStruct.index = index;
- }
- return nameStruct;
- }
- };
- },{}],247:[function(require,module,exports){
- /*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */
- var jpeg = require('./jpeg'),
- exif = require('./exif'),
- simplify = require('./simplify');
- function ExifResult(startMarker, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset) {
- this.startMarker = startMarker;
- this.tags = tags;
- this.imageSize = imageSize;
- this.thumbnailOffset = thumbnailOffset;
- this.thumbnailLength = thumbnailLength;
- this.thumbnailType = thumbnailType;
- this.app1Offset = app1Offset;
- }
- ExifResult.prototype = {
- hasThumbnail: function(mime) {
- if(!this.thumbnailOffset || !this.thumbnailLength) {
- return false;
- }
- if(typeof mime !== 'string') {
- return true;
- }
- if(mime.toLowerCase().trim() === 'image/jpeg') {
- return this.thumbnailType === 6;
- }
- if(mime.toLowerCase().trim() === 'image/tiff') {
- return this.thumbnailType === 1;
- }
- return false;
- },
- getThumbnailOffset: function() {
- return this.app1Offset + 6 + this.thumbnailOffset;
- },
- getThumbnailLength: function() {
- return this.thumbnailLength;
- },
- getThumbnailBuffer: function() {
- return this._getThumbnailStream().nextBuffer(this.thumbnailLength);
- },
- _getThumbnailStream: function() {
- return this.startMarker.openWithOffset(this.getThumbnailOffset());
- },
- getImageSize: function() {
- return this.imageSize;
- },
- getThumbnailSize: function() {
- var stream = this._getThumbnailStream(), size;
- jpeg.parseSections(stream, function(sectionType, sectionStream) {
- if(jpeg.getSectionName(sectionType).name === 'SOF') {
- size = jpeg.getSizeFromSOFSection(sectionStream);
- }
- });
- return size;
- }
- };
- function Parser(stream) {
- this.stream = stream;
- this.flags = {
- readBinaryTags: false,
- resolveTagNames: true,
- simplifyValues: true,
- imageSize: true,
- hidePointers: true,
- returnTags: true
- };
- }
- Parser.prototype = {
- enableBinaryFields: function(enable) {
- this.flags.readBinaryTags = !!enable;
- return this;
- },
- enablePointers: function(enable) {
- this.flags.hidePointers = !enable;
- return this;
- },
- enableTagNames: function(enable) {
- this.flags.resolveTagNames = !!enable;
- return this;
- },
- enableImageSize: function(enable) {
- this.flags.imageSize = !!enable;
- return this;
- },
- enableReturnTags: function(enable) {
- this.flags.returnTags = !!enable;
- return this;
- },
- enableSimpleValues: function(enable) {
- this.flags.simplifyValues = !!enable;
- return this;
- },
- parse: function() {
- var start = this.stream.mark(),
- stream = start.openWithOffset(0),
- flags = this.flags,
- tags,
- imageSize,
- thumbnailOffset,
- thumbnailLength,
- thumbnailType,
- app1Offset,
- tagNames,
- getTagValue, setTagValue;
- if(flags.resolveTagNames) {
- tagNames = require('./exif-tags');
- }
- if(flags.resolveTagNames) {
- tags = {};
- getTagValue = function(t) {
- return tags[t.name];
- };
- setTagValue = function(t, value) {
- tags[t.name] = value;
- };
- } else {
- tags = [];
- getTagValue = function(t) {
- var i;
- for(i = 0; i < tags.length; ++i) {
- if(tags[i].type === t.type && tags[i].section === t.section) {
- return tags.value;
- }
- }
- };
- setTagValue = function(t, value) {
- var i;
- for(i = 0; i < tags.length; ++i) {
- if(tags[i].type === t.type && tags[i].section === t.section) {
- tags.value = value;
- return;
- }
- }
- };
- }
- jpeg.parseSections(stream, function(sectionType, sectionStream) {
- var validExifHeaders, sectionOffset = sectionStream.offsetFrom(start);
- if(sectionType === 0xE1) {
- validExifHeaders = exif.parseTags(sectionStream, function(ifdSection, tagType, value, format) {
- //ignore binary fields if disabled
- if(!flags.readBinaryTags && format === 7) {
- return;
- }
- if(tagType === 0x0201) {
- thumbnailOffset = value[0];
- if(flags.hidePointers) {return;}
- } else if(tagType === 0x0202) {
- thumbnailLength = value[0];
- if(flags.hidePointers) {return;}
- } else if(tagType === 0x0103) {
- thumbnailType = value[0];
- if(flags.hidePointers) {return;}
- }
- //if flag is set to not store tags, return here after storing pointers
- if(!flags.returnTags) {
- return;
- }
- if(flags.simplifyValues) {
- value = simplify.simplifyValue(value, format);
- }
- if(flags.resolveTagNames) {
- var sectionTagNames = ifdSection === exif.GPSIFD ? tagNames.gps : tagNames.exif;
- var name = sectionTagNames[tagType];
- if(!name) {
- name = tagNames.exif[tagType];
- }
- if (!tags.hasOwnProperty(name)) {
- tags[name] = value;
- }
- } else {
- tags.push({
- section: ifdSection,
- type: tagType,
- value: value
- });
- }
- });
- if(validExifHeaders) {
- app1Offset = sectionOffset;
- }
- }
- else if(flags.imageSize && jpeg.getSectionName(sectionType).name === 'SOF') {
- imageSize = jpeg.getSizeFromSOFSection(sectionStream);
- }
- });
- if(flags.simplifyValues) {
- simplify.castDegreeValues(getTagValue, setTagValue);
- simplify.castDateValues(getTagValue, setTagValue);
- }
- return new ExifResult(start, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset);
- }
- };
- module.exports = Parser;
- },{"./exif":245,"./exif-tags":244,"./jpeg":246,"./simplify":248}],248:[function(require,module,exports){
- var exif = require('./exif');
- var date = require('./date');
- var degreeTags = [{
- section: exif.GPSIFD,
- type: 0x0002,
- name: 'GPSLatitude',
- refType: 0x0001,
- refName: 'GPSLatitudeRef',
- posVal: 'N'
- },
- {
- section: exif.GPSIFD,
- type: 0x0004,
- name: 'GPSLongitude',
- refType: 0x0003,
- refName: 'GPSLongitudeRef',
- posVal: 'E'
- }];
- var dateTags = [{
- section: exif.SubIFD,
- type: 0x0132,
- name: 'ModifyDate'
- },
- {
- section: exif.SubIFD,
- type: 0x9003,
- name: 'DateTimeOriginal'
- },
- {
- section: exif.SubIFD,
- type: 0x9004,
- name: 'CreateDate'
- },
- {
- section: exif.SubIFD,
- type: 0x0132,
- name : 'ModifyDate',
- }];
- module.exports = {
- castDegreeValues: function(getTagValue, setTagValue) {
- degreeTags.forEach(function(t) {
- var degreeVal = getTagValue(t);
- if(degreeVal) {
- var degreeRef = getTagValue({section: t.section, type: t.refType, name: t.refName});
- var degreeNumRef = degreeRef === t.posVal ? 1 : -1;
- var degree = (degreeVal[0] + (degreeVal[1] / 60) + (degreeVal[2] / 3600)) * degreeNumRef;
- setTagValue(t, degree);
- }
- });
- },
- castDateValues: function(getTagValue, setTagValue) {
- dateTags.forEach(function(t) {
- var dateStrVal = getTagValue(t);
- if(dateStrVal) {
- //some easy checks to determine two common date formats
- var timestamp = date.parseExifDate(dateStrVal);
- if(typeof timestamp !== 'undefined') {
- setTagValue(t, timestamp);
- }
- }
- });
- },
- simplifyValue: function(values, format) {
- if(Array.isArray(values)) {
- values = values.map(function(value) {
- if(format === 10 || format === 5) {
- return value[0] / value[1];
- }
- return value;
- });
- if(values.length === 1) {
- values = values[0];
- }
- }
- return values;
- }
- };
- },{"./date":242,"./exif":245}],249:[function(require,module,exports){
- 'use strict';
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
- var toBytes = function toBytes(s) {
- return (0, _toConsumableArray2["default"])(s).map(function (c) {
- return c.charCodeAt(0);
- });
- };
- var xpiZipFilename = toBytes('META-INF/mozilla.rsa');
- var oxmlContentTypes = toBytes('[Content_Types].xml');
- var oxmlRels = toBytes('_rels/.rels');
- module.exports = function (input) {
- var buf = input instanceof Uint8Array ? input : new Uint8Array(input);
- if (!(buf && buf.length > 1)) {
- return null;
- }
- var check = function check(header, options) {
- options = Object.assign({
- offset: 0
- }, options);
- for (var i = 0; i < header.length; i++) {
- // If a bitmask is set
- if (options.mask) {
- // If header doesn't equal `buf` with bits masked off
- if (header[i] !== (options.mask[i] & buf[i + options.offset])) {
- return false;
- }
- } else if (header[i] !== buf[i + options.offset]) {
- return false;
- }
- }
- return true;
- };
- var checkString = function checkString(header, options) {
- return check(toBytes(header), options);
- };
- if (check([0xFF, 0xD8, 0xFF])) {
- return {
- ext: 'jpg',
- mime: 'image/jpeg'
- };
- }
- if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
- return {
- ext: 'png',
- mime: 'image/png'
- };
- }
- if (check([0x47, 0x49, 0x46])) {
- return {
- ext: 'gif',
- mime: 'image/gif'
- };
- }
- if (check([0x57, 0x45, 0x42, 0x50], {
- offset: 8
- })) {
- return {
- ext: 'webp',
- mime: 'image/webp'
- };
- }
- if (check([0x46, 0x4C, 0x49, 0x46])) {
- return {
- ext: 'flif',
- mime: 'image/flif'
- };
- } // Needs to be before `tif` check
- if ((check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) && check([0x43, 0x52], {
- offset: 8
- })) {
- return {
- ext: 'cr2',
- mime: 'image/x-canon-cr2'
- };
- }
- if (check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) {
- return {
- ext: 'tif',
- mime: 'image/tiff'
- };
- }
- if (check([0x42, 0x4D])) {
- return {
- ext: 'bmp',
- mime: 'image/bmp'
- };
- }
- if (check([0x49, 0x49, 0xBC])) {
- return {
- ext: 'jxr',
- mime: 'image/vnd.ms-photo'
- };
- }
- if (check([0x38, 0x42, 0x50, 0x53])) {
- return {
- ext: 'psd',
- mime: 'image/vnd.adobe.photoshop'
- };
- } // Zip-based file formats
- // Need to be before the `zip` check
- if (check([0x50, 0x4B, 0x3, 0x4])) {
- if (check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {
- offset: 30
- })) {
- return {
- ext: 'epub',
- mime: 'application/epub+zip'
- };
- } // Assumes signed `.xpi` from addons.mozilla.org
- if (check(xpiZipFilename, {
- offset: 30
- })) {
- return {
- ext: 'xpi',
- mime: 'application/x-xpinstall'
- };
- }
- if (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {
- offset: 30
- })) {
- return {
- ext: 'odt',
- mime: 'application/vnd.oasis.opendocument.text'
- };
- }
- if (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {
- offset: 30
- })) {
- return {
- ext: 'ods',
- mime: 'application/vnd.oasis.opendocument.spreadsheet'
- };
- }
- if (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {
- offset: 30
- })) {
- return {
- ext: 'odp',
- mime: 'application/vnd.oasis.opendocument.presentation'
- };
- } // The docx, xlsx and pptx file types extend the Office Open XML file format:
- // https://en.wikipedia.org/wiki/Office_Open_XML_file_formats
- // We look for:
- // - one entry named '[Content_Types].xml' or '_rels/.rels',
- // - one entry indicating specific type of file.
- // MS Office, OpenOffice and LibreOffice may put the parts in different order, so the check should not rely on it.
- var findNextZipHeaderIndex = function findNextZipHeaderIndex(arr) {
- var startAt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- return arr.findIndex(function (el, i, arr) {
- return i >= startAt && arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4;
- });
- };
- var zipHeaderIndex = 0; // The first zip header was already found at index 0
- var oxmlFound = false;
- var type = null;
- do {
- var offset = zipHeaderIndex + 30;
- if (!oxmlFound) {
- oxmlFound = check(oxmlContentTypes, {
- offset: offset
- }) || check(oxmlRels, {
- offset: offset
- });
- }
- if (!type) {
- if (checkString('word/', {
- offset: offset
- })) {
- type = {
- ext: 'docx',
- mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
- };
- } else if (checkString('ppt/', {
- offset: offset
- })) {
- type = {
- ext: 'pptx',
- mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
- };
- } else if (checkString('xl/', {
- offset: offset
- })) {
- type = {
- ext: 'xlsx',
- mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
- };
- }
- }
- if (oxmlFound && type) {
- return type;
- }
- zipHeaderIndex = findNextZipHeaderIndex(buf, offset);
- } while (zipHeaderIndex >= 0); // No more zip parts available in the buffer, but maybe we are almost certain about the type?
- if (type) {
- return type;
- }
- }
- if (check([0x50, 0x4B]) && (buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) && (buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8)) {
- return {
- ext: 'zip',
- mime: 'application/zip'
- };
- }
- if (check([0x75, 0x73, 0x74, 0x61, 0x72], {
- offset: 257
- })) {
- return {
- ext: 'tar',
- mime: 'application/x-tar'
- };
- }
- if (check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) && (buf[6] === 0x0 || buf[6] === 0x1)) {
- return {
- ext: 'rar',
- mime: 'application/x-rar-compressed'
- };
- }
- if (check([0x1F, 0x8B, 0x8])) {
- return {
- ext: 'gz',
- mime: 'application/gzip'
- };
- }
- if (check([0x42, 0x5A, 0x68])) {
- return {
- ext: 'bz2',
- mime: 'application/x-bzip2'
- };
- }
- if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {
- return {
- ext: '7z',
- mime: 'application/x-7z-compressed'
- };
- }
- if (check([0x78, 0x01])) {
- return {
- ext: 'dmg',
- mime: 'application/x-apple-diskimage'
- };
- }
- if (check([0x33, 0x67, 0x70, 0x35]) || // 3gp5
- check([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {
- offset: 4
- }) && (check([0x6D, 0x70, 0x34, 0x31], {
- offset: 8
- }) || // MP41
- check([0x6D, 0x70, 0x34, 0x32], {
- offset: 8
- }) || // MP42
- check([0x69, 0x73, 0x6F, 0x6D], {
- offset: 8
- }) || // ISOM
- check([0x69, 0x73, 0x6F, 0x32], {
- offset: 8
- }) || // ISO2
- check([0x6D, 0x6D, 0x70, 0x34], {
- offset: 8
- }) || // MMP4
- check([0x4D, 0x34, 0x56], {
- offset: 8
- }) || // M4V
- check([0x64, 0x61, 0x73, 0x68], {
- offset: 8
- }) // DASH
- )) {
- return {
- ext: 'mp4',
- mime: 'video/mp4'
- };
- }
- if (check([0x4D, 0x54, 0x68, 0x64])) {
- return {
- ext: 'mid',
- mime: 'audio/midi'
- };
- } // https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska
- if (check([0x1A, 0x45, 0xDF, 0xA3])) {
- var sliced = buf.subarray(4, 4 + 4096);
- var idPos = sliced.findIndex(function (el, i, arr) {
- return arr[i] === 0x42 && arr[i + 1] === 0x82;
- });
- if (idPos !== -1) {
- var docTypePos = idPos + 3;
- var findDocType = function findDocType(type) {
- return (0, _toConsumableArray2["default"])(type).every(function (c, i) {
- return sliced[docTypePos + i] === c.charCodeAt(0);
- });
- };
- if (findDocType('matroska')) {
- return {
- ext: 'mkv',
- mime: 'video/x-matroska'
- };
- }
- if (findDocType('webm')) {
- return {
- ext: 'webm',
- mime: 'video/webm'
- };
- }
- }
- }
- if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) || check([0x66, 0x72, 0x65, 0x65], {
- offset: 4
- }) || check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {
- offset: 4
- }) || check([0x6D, 0x64, 0x61, 0x74], {
- offset: 4
- }) || // MJPEG
- check([0x77, 0x69, 0x64, 0x65], {
- offset: 4
- })) {
- return {
- ext: 'mov',
- mime: 'video/quicktime'
- };
- } // RIFF file format which might be AVI, WAV, QCP, etc
- if (check([0x52, 0x49, 0x46, 0x46])) {
- if (check([0x41, 0x56, 0x49], {
- offset: 8
- })) {
- return {
- ext: 'avi',
- mime: 'video/vnd.avi'
- };
- }
- if (check([0x57, 0x41, 0x56, 0x45], {
- offset: 8
- })) {
- return {
- ext: 'wav',
- mime: 'audio/vnd.wave'
- };
- } // QLCM, QCP file
- if (check([0x51, 0x4C, 0x43, 0x4D], {
- offset: 8
- })) {
- return {
- ext: 'qcp',
- mime: 'audio/qcelp'
- };
- }
- }
- if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {
- return {
- ext: 'wmv',
- mime: 'video/x-ms-wmv'
- };
- }
- if (check([0x0, 0x0, 0x1, 0xBA]) || check([0x0, 0x0, 0x1, 0xB3])) {
- return {
- ext: 'mpg',
- mime: 'video/mpeg'
- };
- }
- if (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {
- offset: 4
- })) {
- return {
- ext: '3gp',
- mime: 'video/3gpp'
- };
- } // Check for MPEG header at different starting offsets
- for (var start = 0; start < 2 && start < buf.length - 16; start++) {
- if (check([0x49, 0x44, 0x33], {
- offset: start
- }) || // ID3 header
- check([0xFF, 0xE2], {
- offset: start,
- mask: [0xFF, 0xE2]
- }) // MPEG 1 or 2 Layer 3 header
- ) {
- return {
- ext: 'mp3',
- mime: 'audio/mpeg'
- };
- }
- if (check([0xFF, 0xE4], {
- offset: start,
- mask: [0xFF, 0xE4]
- }) // MPEG 1 or 2 Layer 2 header
- ) {
- return {
- ext: 'mp2',
- mime: 'audio/mpeg'
- };
- }
- if (check([0xFF, 0xF8], {
- offset: start,
- mask: [0xFF, 0xFC]
- }) // MPEG 2 layer 0 using ADTS
- ) {
- return {
- ext: 'mp2',
- mime: 'audio/mpeg'
- };
- }
- if (check([0xFF, 0xF0], {
- offset: start,
- mask: [0xFF, 0xFC]
- }) // MPEG 4 layer 0 using ADTS
- ) {
- return {
- ext: 'mp4',
- mime: 'audio/mpeg'
- };
- }
- }
- if (check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {
- offset: 4
- }) || check([0x4D, 0x34, 0x41, 0x20])) {
- return {
- // MPEG-4 layer 3 (audio)
- ext: 'm4a',
- mime: 'audio/mp4' // RFC 4337
- };
- } // Needs to be before `ogg` check
- if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {
- offset: 28
- })) {
- return {
- ext: 'opus',
- mime: 'audio/opus'
- };
- } // If 'OggS' in first bytes, then OGG container
- if (check([0x4F, 0x67, 0x67, 0x53])) {
- // This is a OGG container
- // If ' theora' in header.
- if (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {
- offset: 28
- })) {
- return {
- ext: 'ogv',
- mime: 'video/ogg'
- };
- } // If '\x01video' in header.
- if (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {
- offset: 28
- })) {
- return {
- ext: 'ogm',
- mime: 'video/ogg'
- };
- } // If ' FLAC' in header https://xiph.org/flac/faq.html
- if (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {
- offset: 28
- })) {
- return {
- ext: 'oga',
- mime: 'audio/ogg'
- };
- } // 'Speex ' in header https://en.wikipedia.org/wiki/Speex
- if (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {
- offset: 28
- })) {
- return {
- ext: 'spx',
- mime: 'audio/ogg'
- };
- } // If '\x01vorbis' in header
- if (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {
- offset: 28
- })) {
- return {
- ext: 'ogg',
- mime: 'audio/ogg'
- };
- } // Default OGG container https://www.iana.org/assignments/media-types/application/ogg
- return {
- ext: 'ogx',
- mime: 'application/ogg'
- };
- }
- if (check([0x66, 0x4C, 0x61, 0x43])) {
- return {
- ext: 'flac',
- mime: 'audio/x-flac'
- };
- }
- if (check([0x4D, 0x41, 0x43, 0x20])) {
- // 'MAC '
- return {
- ext: 'ape',
- mime: 'audio/ape'
- };
- }
- if (check([0x77, 0x76, 0x70, 0x6B])) {
- // 'wvpk'
- return {
- ext: 'wv',
- mime: 'audio/wavpack'
- };
- }
- if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) {
- return {
- ext: 'amr',
- mime: 'audio/amr'
- };
- }
- if (check([0x25, 0x50, 0x44, 0x46])) {
- return {
- ext: 'pdf',
- mime: 'application/pdf'
- };
- }
- if (check([0x4D, 0x5A])) {
- return {
- ext: 'exe',
- mime: 'application/x-msdownload'
- };
- }
- if ((buf[0] === 0x43 || buf[0] === 0x46) && check([0x57, 0x53], {
- offset: 1
- })) {
- return {
- ext: 'swf',
- mime: 'application/x-shockwave-flash'
- };
- }
- if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) {
- return {
- ext: 'rtf',
- mime: 'application/rtf'
- };
- }
- if (check([0x00, 0x61, 0x73, 0x6D])) {
- return {
- ext: 'wasm',
- mime: 'application/wasm'
- };
- }
- if (check([0x77, 0x4F, 0x46, 0x46]) && (check([0x00, 0x01, 0x00, 0x00], {
- offset: 4
- }) || check([0x4F, 0x54, 0x54, 0x4F], {
- offset: 4
- }))) {
- return {
- ext: 'woff',
- mime: 'font/woff'
- };
- }
- if (check([0x77, 0x4F, 0x46, 0x32]) && (check([0x00, 0x01, 0x00, 0x00], {
- offset: 4
- }) || check([0x4F, 0x54, 0x54, 0x4F], {
- offset: 4
- }))) {
- return {
- ext: 'woff2',
- mime: 'font/woff2'
- };
- }
- if (check([0x4C, 0x50], {
- offset: 34
- }) && (check([0x00, 0x00, 0x01], {
- offset: 8
- }) || check([0x01, 0x00, 0x02], {
- offset: 8
- }) || check([0x02, 0x00, 0x02], {
- offset: 8
- }))) {
- return {
- ext: 'eot',
- mime: 'application/vnd.ms-fontobject'
- };
- }
- if (check([0x00, 0x01, 0x00, 0x00, 0x00])) {
- return {
- ext: 'ttf',
- mime: 'font/ttf'
- };
- }
- if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {
- return {
- ext: 'otf',
- mime: 'font/otf'
- };
- }
- if (check([0x00, 0x00, 0x01, 0x00])) {
- return {
- ext: 'ico',
- mime: 'image/x-icon'
- };
- }
- if (check([0x00, 0x00, 0x02, 0x00])) {
- return {
- ext: 'cur',
- mime: 'image/x-icon'
- };
- }
- if (check([0x46, 0x4C, 0x56, 0x01])) {
- return {
- ext: 'flv',
- mime: 'video/x-flv'
- };
- }
- if (check([0x25, 0x21])) {
- return {
- ext: 'ps',
- mime: 'application/postscript'
- };
- }
- if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {
- return {
- ext: 'xz',
- mime: 'application/x-xz'
- };
- }
- if (check([0x53, 0x51, 0x4C, 0x69])) {
- return {
- ext: 'sqlite',
- mime: 'application/x-sqlite3'
- };
- }
- if (check([0x4E, 0x45, 0x53, 0x1A])) {
- return {
- ext: 'nes',
- mime: 'application/x-nintendo-nes-rom'
- };
- }
- if (check([0x43, 0x72, 0x32, 0x34])) {
- return {
- ext: 'crx',
- mime: 'application/x-google-chrome-extension'
- };
- }
- if (check([0x4D, 0x53, 0x43, 0x46]) || check([0x49, 0x53, 0x63, 0x28])) {
- return {
- ext: 'cab',
- mime: 'application/vnd.ms-cab-compressed'
- };
- } // Needs to be before `ar` check
- if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) {
- return {
- ext: 'deb',
- mime: 'application/x-deb'
- };
- }
- if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) {
- return {
- ext: 'ar',
- mime: 'application/x-unix-archive'
- };
- }
- if (check([0xED, 0xAB, 0xEE, 0xDB])) {
- return {
- ext: 'rpm',
- mime: 'application/x-rpm'
- };
- }
- if (check([0x1F, 0xA0]) || check([0x1F, 0x9D])) {
- return {
- ext: 'Z',
- mime: 'application/x-compress'
- };
- }
- if (check([0x4C, 0x5A, 0x49, 0x50])) {
- return {
- ext: 'lz',
- mime: 'application/x-lzip'
- };
- }
- if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {
- return {
- ext: 'msi',
- mime: 'application/x-msi'
- };
- }
- if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {
- return {
- ext: 'mxf',
- mime: 'application/mxf'
- };
- }
- if (check([0x47], {
- offset: 4
- }) && (check([0x47], {
- offset: 192
- }) || check([0x47], {
- offset: 196
- }))) {
- return {
- ext: 'mts',
- mime: 'video/mp2t'
- };
- }
- if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) {
- return {
- ext: 'blend',
- mime: 'application/x-blender'
- };
- }
- if (check([0x42, 0x50, 0x47, 0xFB])) {
- return {
- ext: 'bpg',
- mime: 'image/bpg'
- };
- }
- if (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {
- // JPEG-2000 family
- if (check([0x6A, 0x70, 0x32, 0x20], {
- offset: 20
- })) {
- return {
- ext: 'jp2',
- mime: 'image/jp2'
- };
- }
- if (check([0x6A, 0x70, 0x78, 0x20], {
- offset: 20
- })) {
- return {
- ext: 'jpx',
- mime: 'image/jpx'
- };
- }
- if (check([0x6A, 0x70, 0x6D, 0x20], {
- offset: 20
- })) {
- return {
- ext: 'jpm',
- mime: 'image/jpm'
- };
- }
- if (check([0x6D, 0x6A, 0x70, 0x32], {
- offset: 20
- })) {
- return {
- ext: 'mj2',
- mime: 'image/mj2'
- };
- }
- }
- if (check([0x46, 0x4F, 0x52, 0x4D, 0x00])) {
- return {
- ext: 'aif',
- mime: 'audio/aiff'
- };
- }
- if (checkString('<?xml ')) {
- return {
- ext: 'xml',
- mime: 'application/xml'
- };
- }
- if (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {
- offset: 60
- })) {
- return {
- ext: 'mobi',
- mime: 'application/x-mobipocket-ebook'
- };
- } // File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format)
- if (check([0x66, 0x74, 0x79, 0x70], {
- offset: 4
- })) {
- if (check([0x6D, 0x69, 0x66, 0x31], {
- offset: 8
- })) {
- return {
- ext: 'heic',
- mime: 'image/heif'
- };
- }
- if (check([0x6D, 0x73, 0x66, 0x31], {
- offset: 8
- })) {
- return {
- ext: 'heic',
- mime: 'image/heif-sequence'
- };
- }
- if (check([0x68, 0x65, 0x69, 0x63], {
- offset: 8
- }) || check([0x68, 0x65, 0x69, 0x78], {
- offset: 8
- })) {
- return {
- ext: 'heic',
- mime: 'image/heic'
- };
- }
- if (check([0x68, 0x65, 0x76, 0x63], {
- offset: 8
- }) || check([0x68, 0x65, 0x76, 0x78], {
- offset: 8
- })) {
- return {
- ext: 'heic',
- mime: 'image/heic-sequence'
- };
- }
- }
- if (check([0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A])) {
- return {
- ext: 'ktx',
- mime: 'image/ktx'
- };
- }
- return null;
- };
- },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/toConsumableArray":19}],250:[function(require,module,exports){
- 'use strict';
- var isCallable = require('is-callable');
- var toStr = Object.prototype.toString;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var forEachArray = function forEachArray(array, iterator, receiver) {
- for (var i = 0, len = array.length; i < len; i++) {
- if (hasOwnProperty.call(array, i)) {
- if (receiver == null) {
- iterator(array[i], i, array);
- } else {
- iterator.call(receiver, array[i], i, array);
- }
- }
- }
- };
- var forEachString = function forEachString(string, iterator, receiver) {
- for (var i = 0, len = string.length; i < len; i++) {
- // no such thing as a sparse string.
- if (receiver == null) {
- iterator(string.charAt(i), i, string);
- } else {
- iterator.call(receiver, string.charAt(i), i, string);
- }
- }
- };
- var forEachObject = function forEachObject(object, iterator, receiver) {
- for (var k in object) {
- if (hasOwnProperty.call(object, k)) {
- if (receiver == null) {
- iterator(object[k], k, object);
- } else {
- iterator.call(receiver, object[k], k, object);
- }
- }
- }
- };
- var forEach = function forEach(list, iterator, thisArg) {
- if (!isCallable(iterator)) {
- throw new TypeError('iterator must be a function');
- }
- var receiver;
- if (arguments.length >= 3) {
- receiver = thisArg;
- }
- if (toStr.call(list) === '[object Array]') {
- forEachArray(list, iterator, receiver);
- } else if (typeof list === 'string') {
- forEachString(list, iterator, receiver);
- } else {
- forEachObject(list, iterator, receiver);
- }
- };
- module.exports = forEach;
- },{"is-callable":256}],251:[function(require,module,exports){
- (function (global){
- var win;
- if (typeof window !== "undefined") {
- win = window;
- } else if (typeof global !== "undefined") {
- win = global;
- } else if (typeof self !== "undefined"){
- win = self;
- } else {
- win = {};
- }
- module.exports = win;
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],252:[function(require,module,exports){
- var http = require('http')
- var url = require('url')
- var https = module.exports
- for (var key in http) {
- if (http.hasOwnProperty(key)) https[key] = http[key]
- }
- https.request = function (params, cb) {
- params = validateParams(params)
- return http.request.call(this, params, cb)
- }
- https.get = function (params, cb) {
- params = validateParams(params)
- return http.get.call(this, params, cb)
- }
- function validateParams (params) {
- if (typeof params === 'string') {
- params = url.parse(params)
- }
- if (!params.protocol) {
- params.protocol = 'https:'
- }
- if (params.protocol !== 'https:') {
- throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
- }
- return params
- }
- },{"http":335,"url":359}],253:[function(require,module,exports){
- exports.read = function (buffer, offset, isLE, mLen, nBytes) {
- var e, m
- var eLen = (nBytes * 8) - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var nBits = -7
- var i = isLE ? (nBytes - 1) : 0
- var d = isLE ? -1 : 1
- var s = buffer[offset + i]
- i += d
- e = s & ((1 << (-nBits)) - 1)
- s >>= (-nBits)
- nBits += eLen
- for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
- m = e & ((1 << (-nBits)) - 1)
- e >>= (-nBits)
- nBits += mLen
- for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
- if (e === 0) {
- e = 1 - eBias
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity)
- } else {
- m = m + Math.pow(2, mLen)
- e = e - eBias
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
- }
- exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
- var e, m, c
- var eLen = (nBytes * 8) - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
- var i = isLE ? 0 : (nBytes - 1)
- var d = isLE ? 1 : -1
- var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
- value = Math.abs(value)
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0
- e = eMax
- } else {
- e = Math.floor(Math.log(value) / Math.LN2)
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--
- c *= 2
- }
- if (e + eBias >= 1) {
- value += rt / c
- } else {
- value += rt * Math.pow(2, 1 - eBias)
- }
- if (value * c >= 2) {
- e++
- c /= 2
- }
- if (e + eBias >= eMax) {
- m = 0
- e = eMax
- } else if (e + eBias >= 1) {
- m = ((value * c) - 1) * Math.pow(2, mLen)
- e = e + eBias
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
- e = 0
- }
- }
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
- e = (e << mLen) | m
- eLen += mLen
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
- buffer[offset + i - d] |= s * 128
- }
- },{}],254:[function(require,module,exports){
- if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- })
- }
- };
- } else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
- }
- }
- },{}],255:[function(require,module,exports){
- /*!
- * Determine if an object is a Buffer
- *
- * @author Feross Aboukhadijeh <https://feross.org>
- * @license MIT
- */
- // The _isBuffer check is for Safari 5-7 support, because it's missing
- // Object.prototype.constructor. Remove this eventually
- module.exports = function (obj) {
- return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
- }
- function isBuffer (obj) {
- return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
- }
- // For Node v0.10 support. Remove this eventually.
- function isSlowBuffer (obj) {
- return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
- }
- },{}],256:[function(require,module,exports){
- 'use strict';
- var fnToStr = Function.prototype.toString;
- var constructorRegex = /^\s*class\b/;
- var isES6ClassFn = function isES6ClassFunction(value) {
- try {
- var fnStr = fnToStr.call(value);
- return constructorRegex.test(fnStr);
- } catch (e) {
- return false; // not a function
- }
- };
- var tryFunctionObject = function tryFunctionToStr(value) {
- try {
- if (isES6ClassFn(value)) { return false; }
- fnToStr.call(value);
- return true;
- } catch (e) {
- return false;
- }
- };
- var toStr = Object.prototype.toString;
- var fnClass = '[object Function]';
- var genClass = '[object GeneratorFunction]';
- var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
- module.exports = function isCallable(value) {
- if (!value) { return false; }
- if (typeof value !== 'function' && typeof value !== 'object') { return false; }
- if (typeof value === 'function' && !value.prototype) { return true; }
- if (hasToStringTag) { return tryFunctionObject(value); }
- if (isES6ClassFn(value)) { return false; }
- var strClass = toStr.call(value);
- return strClass === fnClass || strClass === genClass;
- };
- },{}],257:[function(require,module,exports){
- module.exports = isFunction
- var toString = Object.prototype.toString
- function isFunction (fn) {
- var string = toString.call(fn)
- return string === '[object Function]' ||
- (typeof fn === 'function' && string !== '[object RegExp]') ||
- (typeof window !== 'undefined' &&
- // IE8 and below
- (fn === window.setTimeout ||
- fn === window.alert ||
- fn === window.confirm ||
- fn === window.prompt))
- };
- },{}],258:[function(require,module,exports){
- var toString = {}.toString;
- module.exports = Array.isArray || function (arr) {
- return toString.call(arr) == '[object Array]';
- };
- },{}],259:[function(require,module,exports){
- var encode = require('./lib/encoder'),
- decode = require('./lib/decoder');
- module.exports = {
- encode: encode,
- decode: decode
- };
- },{"./lib/decoder":260,"./lib/encoder":261}],260:[function(require,module,exports){
- (function (Buffer){
- /* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
- /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
- /*
- Copyright 2011 notmasteryet
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
- // - The JPEG specification can be found in the ITU CCITT Recommendation T.81
- // (www.w3.org/Graphics/JPEG/itu-t81.pdf)
- // - The JFIF specification can be found in the JPEG File Interchange Format
- // (www.w3.org/Graphics/JPEG/jfif3.pdf)
- // - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters
- // in PostScript Level 2, Technical Note #5116
- // (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)
- var JpegImage = (function jpegImage() {
- "use strict";
- var dctZigZag = new Int32Array([
- 0,
- 1, 8,
- 16, 9, 2,
- 3, 10, 17, 24,
- 32, 25, 18, 11, 4,
- 5, 12, 19, 26, 33, 40,
- 48, 41, 34, 27, 20, 13, 6,
- 7, 14, 21, 28, 35, 42, 49, 56,
- 57, 50, 43, 36, 29, 22, 15,
- 23, 30, 37, 44, 51, 58,
- 59, 52, 45, 38, 31,
- 39, 46, 53, 60,
- 61, 54, 47,
- 55, 62,
- 63
- ]);
- var dctCos1 = 4017 // cos(pi/16)
- var dctSin1 = 799 // sin(pi/16)
- var dctCos3 = 3406 // cos(3*pi/16)
- var dctSin3 = 2276 // sin(3*pi/16)
- var dctCos6 = 1567 // cos(6*pi/16)
- var dctSin6 = 3784 // sin(6*pi/16)
- var dctSqrt2 = 5793 // sqrt(2)
- var dctSqrt1d2 = 2896 // sqrt(2) / 2
- function constructor() {
- }
- function buildHuffmanTable(codeLengths, values) {
- var k = 0, code = [], i, j, length = 16;
- while (length > 0 && !codeLengths[length - 1])
- length--;
- code.push({children: [], index: 0});
- var p = code[0], q;
- for (i = 0; i < length; i++) {
- for (j = 0; j < codeLengths[i]; j++) {
- p = code.pop();
- p.children[p.index] = values[k];
- while (p.index > 0) {
- p = code.pop();
- }
- p.index++;
- code.push(p);
- while (code.length <= i) {
- code.push(q = {children: [], index: 0});
- p.children[p.index] = q.children;
- p = q;
- }
- k++;
- }
- if (i + 1 < length) {
- // p here points to last code
- code.push(q = {children: [], index: 0});
- p.children[p.index] = q.children;
- p = q;
- }
- }
- return code[0].children;
- }
- function decodeScan(data, offset,
- frame, components, resetInterval,
- spectralStart, spectralEnd,
- successivePrev, successive) {
- var precision = frame.precision;
- var samplesPerLine = frame.samplesPerLine;
- var scanLines = frame.scanLines;
- var mcusPerLine = frame.mcusPerLine;
- var progressive = frame.progressive;
- var maxH = frame.maxH, maxV = frame.maxV;
- var startOffset = offset, bitsData = 0, bitsCount = 0;
- function readBit() {
- if (bitsCount > 0) {
- bitsCount--;
- return (bitsData >> bitsCount) & 1;
- }
- bitsData = data[offset++];
- if (bitsData == 0xFF) {
- var nextByte = data[offset++];
- if (nextByte) {
- throw new Error("unexpected marker: " + ((bitsData << 8) | nextByte).toString(16));
- }
- // unstuff 0
- }
- bitsCount = 7;
- return bitsData >>> 7;
- }
- function decodeHuffman(tree) {
- var node = tree, bit;
- while ((bit = readBit()) !== null) {
- node = node[bit];
- if (typeof node === 'number')
- return node;
- if (typeof node !== 'object')
- throw new Error("invalid huffman sequence");
- }
- return null;
- }
- function receive(length) {
- var n = 0;
- while (length > 0) {
- var bit = readBit();
- if (bit === null) return;
- n = (n << 1) | bit;
- length--;
- }
- return n;
- }
- function receiveAndExtend(length) {
- var n = receive(length);
- if (n >= 1 << (length - 1))
- return n;
- return n + (-1 << length) + 1;
- }
- function decodeBaseline(component, zz) {
- var t = decodeHuffman(component.huffmanTableDC);
- var diff = t === 0 ? 0 : receiveAndExtend(t);
- zz[0]= (component.pred += diff);
- var k = 1;
- while (k < 64) {
- var rs = decodeHuffman(component.huffmanTableAC);
- var s = rs & 15, r = rs >> 4;
- if (s === 0) {
- if (r < 15)
- break;
- k += 16;
- continue;
- }
- k += r;
- var z = dctZigZag[k];
- zz[z] = receiveAndExtend(s);
- k++;
- }
- }
- function decodeDCFirst(component, zz) {
- var t = decodeHuffman(component.huffmanTableDC);
- var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
- zz[0] = (component.pred += diff);
- }
- function decodeDCSuccessive(component, zz) {
- zz[0] |= readBit() << successive;
- }
- var eobrun = 0;
- function decodeACFirst(component, zz) {
- if (eobrun > 0) {
- eobrun--;
- return;
- }
- var k = spectralStart, e = spectralEnd;
- while (k <= e) {
- var rs = decodeHuffman(component.huffmanTableAC);
- var s = rs & 15, r = rs >> 4;
- if (s === 0) {
- if (r < 15) {
- eobrun = receive(r) + (1 << r) - 1;
- break;
- }
- k += 16;
- continue;
- }
- k += r;
- var z = dctZigZag[k];
- zz[z] = receiveAndExtend(s) * (1 << successive);
- k++;
- }
- }
- var successiveACState = 0, successiveACNextValue;
- function decodeACSuccessive(component, zz) {
- var k = spectralStart, e = spectralEnd, r = 0;
- while (k <= e) {
- var z = dctZigZag[k];
- var direction = zz[z] < 0 ? -1 : 1;
- switch (successiveACState) {
- case 0: // initial state
- var rs = decodeHuffman(component.huffmanTableAC);
- var s = rs & 15, r = rs >> 4;
- if (s === 0) {
- if (r < 15) {
- eobrun = receive(r) + (1 << r);
- successiveACState = 4;
- } else {
- r = 16;
- successiveACState = 1;
- }
- } else {
- if (s !== 1)
- throw new Error("invalid ACn encoding");
- successiveACNextValue = receiveAndExtend(s);
- successiveACState = r ? 2 : 3;
- }
- continue;
- case 1: // skipping r zero items
- case 2:
- if (zz[z])
- zz[z] += (readBit() << successive) * direction;
- else {
- r--;
- if (r === 0)
- successiveACState = successiveACState == 2 ? 3 : 0;
- }
- break;
- case 3: // set value for a zero item
- if (zz[z])
- zz[z] += (readBit() << successive) * direction;
- else {
- zz[z] = successiveACNextValue << successive;
- successiveACState = 0;
- }
- break;
- case 4: // eob
- if (zz[z])
- zz[z] += (readBit() << successive) * direction;
- break;
- }
- k++;
- }
- if (successiveACState === 4) {
- eobrun--;
- if (eobrun === 0)
- successiveACState = 0;
- }
- }
- function decodeMcu(component, decode, mcu, row, col) {
- var mcuRow = (mcu / mcusPerLine) | 0;
- var mcuCol = mcu % mcusPerLine;
- var blockRow = mcuRow * component.v + row;
- var blockCol = mcuCol * component.h + col;
- decode(component, component.blocks[blockRow][blockCol]);
- }
- function decodeBlock(component, decode, mcu) {
- var blockRow = (mcu / component.blocksPerLine) | 0;
- var blockCol = mcu % component.blocksPerLine;
- decode(component, component.blocks[blockRow][blockCol]);
- }
- var componentsLength = components.length;
- var component, i, j, k, n;
- var decodeFn;
- if (progressive) {
- if (spectralStart === 0)
- decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
- else
- decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
- } else {
- decodeFn = decodeBaseline;
- }
- var mcu = 0, marker;
- var mcuExpected;
- if (componentsLength == 1) {
- mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
- } else {
- mcuExpected = mcusPerLine * frame.mcusPerColumn;
- }
- if (!resetInterval) resetInterval = mcuExpected;
- var h, v;
- while (mcu < mcuExpected) {
- // reset interval stuff
- for (i = 0; i < componentsLength; i++)
- components[i].pred = 0;
- eobrun = 0;
- if (componentsLength == 1) {
- component = components[0];
- for (n = 0; n < resetInterval; n++) {
- decodeBlock(component, decodeFn, mcu);
- mcu++;
- }
- } else {
- for (n = 0; n < resetInterval; n++) {
- for (i = 0; i < componentsLength; i++) {
- component = components[i];
- h = component.h;
- v = component.v;
- for (j = 0; j < v; j++) {
- for (k = 0; k < h; k++) {
- decodeMcu(component, decodeFn, mcu, j, k);
- }
- }
- }
- mcu++;
- // If we've reached our expected MCU's, stop decoding
- if (mcu === mcuExpected) break;
- }
- }
- // find marker
- bitsCount = 0;
- marker = (data[offset] << 8) | data[offset + 1];
- if (marker < 0xFF00) {
- throw new Error("marker was not found");
- }
- if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
- offset += 2;
- }
- else
- break;
- }
- return offset - startOffset;
- }
- function buildComponentData(frame, component) {
- var lines = [];
- var blocksPerLine = component.blocksPerLine;
- var blocksPerColumn = component.blocksPerColumn;
- var samplesPerLine = blocksPerLine << 3;
- var R = new Int32Array(64), r = new Uint8Array(64);
- // A port of poppler's IDCT method which in turn is taken from:
- // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
- // "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
- // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
- // 988-991.
- function quantizeAndInverse(zz, dataOut, dataIn) {
- var qt = component.quantizationTable;
- var v0, v1, v2, v3, v4, v5, v6, v7, t;
- var p = dataIn;
- var i;
- // dequant
- for (i = 0; i < 64; i++)
- p[i] = zz[i] * qt[i];
- // inverse DCT on rows
- for (i = 0; i < 8; ++i) {
- var row = 8 * i;
- // check for all-zero AC coefficients
- if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&
- p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&
- p[7 + row] == 0) {
- t = (dctSqrt2 * p[0 + row] + 512) >> 10;
- p[0 + row] = t;
- p[1 + row] = t;
- p[2 + row] = t;
- p[3 + row] = t;
- p[4 + row] = t;
- p[5 + row] = t;
- p[6 + row] = t;
- p[7 + row] = t;
- continue;
- }
- // stage 4
- v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;
- v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;
- v2 = p[2 + row];
- v3 = p[6 + row];
- v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;
- v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;
- v5 = p[3 + row] << 4;
- v6 = p[5 + row] << 4;
- // stage 3
- t = (v0 - v1+ 1) >> 1;
- v0 = (v0 + v1 + 1) >> 1;
- v1 = t;
- t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
- v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
- v3 = t;
- t = (v4 - v6 + 1) >> 1;
- v4 = (v4 + v6 + 1) >> 1;
- v6 = t;
- t = (v7 + v5 + 1) >> 1;
- v5 = (v7 - v5 + 1) >> 1;
- v7 = t;
- // stage 2
- t = (v0 - v3 + 1) >> 1;
- v0 = (v0 + v3 + 1) >> 1;
- v3 = t;
- t = (v1 - v2 + 1) >> 1;
- v1 = (v1 + v2 + 1) >> 1;
- v2 = t;
- t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
- v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
- v7 = t;
- t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
- v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
- v6 = t;
- // stage 1
- p[0 + row] = v0 + v7;
- p[7 + row] = v0 - v7;
- p[1 + row] = v1 + v6;
- p[6 + row] = v1 - v6;
- p[2 + row] = v2 + v5;
- p[5 + row] = v2 - v5;
- p[3 + row] = v3 + v4;
- p[4 + row] = v3 - v4;
- }
- // inverse DCT on columns
- for (i = 0; i < 8; ++i) {
- var col = i;
- // check for all-zero AC coefficients
- if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 &&
- p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 &&
- p[7*8 + col] == 0) {
- t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;
- p[0*8 + col] = t;
- p[1*8 + col] = t;
- p[2*8 + col] = t;
- p[3*8 + col] = t;
- p[4*8 + col] = t;
- p[5*8 + col] = t;
- p[6*8 + col] = t;
- p[7*8 + col] = t;
- continue;
- }
- // stage 4
- v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12;
- v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12;
- v2 = p[2*8 + col];
- v3 = p[6*8 + col];
- v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12;
- v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12;
- v5 = p[3*8 + col];
- v6 = p[5*8 + col];
- // stage 3
- t = (v0 - v1 + 1) >> 1;
- v0 = (v0 + v1 + 1) >> 1;
- v1 = t;
- t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
- v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
- v3 = t;
- t = (v4 - v6 + 1) >> 1;
- v4 = (v4 + v6 + 1) >> 1;
- v6 = t;
- t = (v7 + v5 + 1) >> 1;
- v5 = (v7 - v5 + 1) >> 1;
- v7 = t;
- // stage 2
- t = (v0 - v3 + 1) >> 1;
- v0 = (v0 + v3 + 1) >> 1;
- v3 = t;
- t = (v1 - v2 + 1) >> 1;
- v1 = (v1 + v2 + 1) >> 1;
- v2 = t;
- t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
- v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
- v7 = t;
- t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
- v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
- v6 = t;
- // stage 1
- p[0*8 + col] = v0 + v7;
- p[7*8 + col] = v0 - v7;
- p[1*8 + col] = v1 + v6;
- p[6*8 + col] = v1 - v6;
- p[2*8 + col] = v2 + v5;
- p[5*8 + col] = v2 - v5;
- p[3*8 + col] = v3 + v4;
- p[4*8 + col] = v3 - v4;
- }
- // convert to 8-bit integers
- for (i = 0; i < 64; ++i) {
- var sample = 128 + ((p[i] + 8) >> 4);
- dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;
- }
- }
- var i, j;
- for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
- var scanLine = blockRow << 3;
- for (i = 0; i < 8; i++)
- lines.push(new Uint8Array(samplesPerLine));
- for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
- quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);
- var offset = 0, sample = blockCol << 3;
- for (j = 0; j < 8; j++) {
- var line = lines[scanLine + j];
- for (i = 0; i < 8; i++)
- line[sample + i] = r[offset++];
- }
- }
- }
- return lines;
- }
- function clampTo8bit(a) {
- return a < 0 ? 0 : a > 255 ? 255 : a;
- }
- constructor.prototype = {
- load: function load(path) {
- var xhr = new XMLHttpRequest();
- xhr.open("GET", path, true);
- xhr.responseType = "arraybuffer";
- xhr.onload = (function() {
- // TODO catch parse error
- var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
- this.parse(data);
- if (this.onload)
- this.onload();
- }).bind(this);
- xhr.send(null);
- },
- parse: function parse(data) {
- var offset = 0, length = data.length;
- function readUint16() {
- var value = (data[offset] << 8) | data[offset + 1];
- offset += 2;
- return value;
- }
- function readDataBlock() {
- var length = readUint16();
- var array = data.subarray(offset, offset + length - 2);
- offset += array.length;
- return array;
- }
- function prepareComponents(frame) {
- var maxH = 0, maxV = 0;
- var component, componentId;
- for (componentId in frame.components) {
- if (frame.components.hasOwnProperty(componentId)) {
- component = frame.components[componentId];
- if (maxH < component.h) maxH = component.h;
- if (maxV < component.v) maxV = component.v;
- }
- }
- var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
- var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
- for (componentId in frame.components) {
- if (frame.components.hasOwnProperty(componentId)) {
- component = frame.components[componentId];
- var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
- var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
- var blocksPerLineForMcu = mcusPerLine * component.h;
- var blocksPerColumnForMcu = mcusPerColumn * component.v;
- var blocks = [];
- for (var i = 0; i < blocksPerColumnForMcu; i++) {
- var row = [];
- for (var j = 0; j < blocksPerLineForMcu; j++)
- row.push(new Int32Array(64));
- blocks.push(row);
- }
- component.blocksPerLine = blocksPerLine;
- component.blocksPerColumn = blocksPerColumn;
- component.blocks = blocks;
- }
- }
- frame.maxH = maxH;
- frame.maxV = maxV;
- frame.mcusPerLine = mcusPerLine;
- frame.mcusPerColumn = mcusPerColumn;
- }
- var jfif = null;
- var adobe = null;
- var pixels = null;
- var frame, resetInterval;
- var quantizationTables = [], frames = [];
- var huffmanTablesAC = [], huffmanTablesDC = [];
- var fileMarker = readUint16();
- if (fileMarker != 0xFFD8) { // SOI (Start of Image)
- throw new Error("SOI not found");
- }
- fileMarker = readUint16();
- while (fileMarker != 0xFFD9) { // EOI (End of image)
- var i, j, l;
- switch(fileMarker) {
- case 0xFF00: break;
- case 0xFFE0: // APP0 (Application Specific)
- case 0xFFE1: // APP1
- case 0xFFE2: // APP2
- case 0xFFE3: // APP3
- case 0xFFE4: // APP4
- case 0xFFE5: // APP5
- case 0xFFE6: // APP6
- case 0xFFE7: // APP7
- case 0xFFE8: // APP8
- case 0xFFE9: // APP9
- case 0xFFEA: // APP10
- case 0xFFEB: // APP11
- case 0xFFEC: // APP12
- case 0xFFED: // APP13
- case 0xFFEE: // APP14
- case 0xFFEF: // APP15
- case 0xFFFE: // COM (Comment)
- var appData = readDataBlock();
- if (fileMarker === 0xFFE0) {
- if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&
- appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00'
- jfif = {
- version: { major: appData[5], minor: appData[6] },
- densityUnits: appData[7],
- xDensity: (appData[8] << 8) | appData[9],
- yDensity: (appData[10] << 8) | appData[11],
- thumbWidth: appData[12],
- thumbHeight: appData[13],
- thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
- };
- }
- }
- // TODO APP1 - Exif
- if (fileMarker === 0xFFEE) {
- if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&
- appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00'
- adobe = {
- version: appData[6],
- flags0: (appData[7] << 8) | appData[8],
- flags1: (appData[9] << 8) | appData[10],
- transformCode: appData[11]
- };
- }
- }
- break;
- case 0xFFDB: // DQT (Define Quantization Tables)
- var quantizationTablesLength = readUint16();
- var quantizationTablesEnd = quantizationTablesLength + offset - 2;
- while (offset < quantizationTablesEnd) {
- var quantizationTableSpec = data[offset++];
- var tableData = new Int32Array(64);
- if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
- for (j = 0; j < 64; j++) {
- var z = dctZigZag[j];
- tableData[z] = data[offset++];
- }
- } else if ((quantizationTableSpec >> 4) === 1) { //16 bit
- for (j = 0; j < 64; j++) {
- var z = dctZigZag[j];
- tableData[z] = readUint16();
- }
- } else
- throw new Error("DQT: invalid table spec");
- quantizationTables[quantizationTableSpec & 15] = tableData;
- }
- break;
- case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
- case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
- case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
- readUint16(); // skip data length
- frame = {};
- frame.extended = (fileMarker === 0xFFC1);
- frame.progressive = (fileMarker === 0xFFC2);
- frame.precision = data[offset++];
- frame.scanLines = readUint16();
- frame.samplesPerLine = readUint16();
- frame.components = {};
- frame.componentsOrder = [];
- var componentsCount = data[offset++], componentId;
- var maxH = 0, maxV = 0;
- for (i = 0; i < componentsCount; i++) {
- componentId = data[offset];
- var h = data[offset + 1] >> 4;
- var v = data[offset + 1] & 15;
- var qId = data[offset + 2];
- frame.componentsOrder.push(componentId);
- frame.components[componentId] = {
- h: h,
- v: v,
- quantizationIdx: qId
- };
- offset += 3;
- }
- prepareComponents(frame);
- frames.push(frame);
- break;
- case 0xFFC4: // DHT (Define Huffman Tables)
- var huffmanLength = readUint16();
- for (i = 2; i < huffmanLength;) {
- var huffmanTableSpec = data[offset++];
- var codeLengths = new Uint8Array(16);
- var codeLengthSum = 0;
- for (j = 0; j < 16; j++, offset++)
- codeLengthSum += (codeLengths[j] = data[offset]);
- var huffmanValues = new Uint8Array(codeLengthSum);
- for (j = 0; j < codeLengthSum; j++, offset++)
- huffmanValues[j] = data[offset];
- i += 17 + codeLengthSum;
- ((huffmanTableSpec >> 4) === 0 ?
- huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
- buildHuffmanTable(codeLengths, huffmanValues);
- }
- break;
- case 0xFFDD: // DRI (Define Restart Interval)
- readUint16(); // skip data length
- resetInterval = readUint16();
- break;
- case 0xFFDA: // SOS (Start of Scan)
- var scanLength = readUint16();
- var selectorsCount = data[offset++];
- var components = [], component;
- for (i = 0; i < selectorsCount; i++) {
- component = frame.components[data[offset++]];
- var tableSpec = data[offset++];
- component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
- component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
- components.push(component);
- }
- var spectralStart = data[offset++];
- var spectralEnd = data[offset++];
- var successiveApproximation = data[offset++];
- var processed = decodeScan(data, offset,
- frame, components, resetInterval,
- spectralStart, spectralEnd,
- successiveApproximation >> 4, successiveApproximation & 15);
- offset += processed;
- break;
- case 0xFFFF: // Fill bytes
- if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
- offset--;
- }
- break;
- default:
- if (data[offset - 3] == 0xFF &&
- data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
- // could be incorrect encoding -- last 0xFF byte of the previous
- // block was eaten by the encoder
- offset -= 3;
- break;
- }
- throw new Error("unknown JPEG marker " + fileMarker.toString(16));
- }
- fileMarker = readUint16();
- }
- if (frames.length != 1)
- throw new Error("only single frame JPEGs supported");
- // set each frame's components quantization table
- for (var i = 0; i < frames.length; i++) {
- var cp = frames[i].components;
- for (var j in cp) {
- cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
- delete cp[j].quantizationIdx;
- }
- }
- this.width = frame.samplesPerLine;
- this.height = frame.scanLines;
- this.jfif = jfif;
- this.adobe = adobe;
- this.components = [];
- for (var i = 0; i < frame.componentsOrder.length; i++) {
- var component = frame.components[frame.componentsOrder[i]];
- this.components.push({
- lines: buildComponentData(frame, component),
- scaleX: component.h / frame.maxH,
- scaleY: component.v / frame.maxV
- });
- }
- },
- getData: function getData(width, height) {
- var scaleX = this.width / width, scaleY = this.height / height;
- var component1, component2, component3, component4;
- var component1Line, component2Line, component3Line, component4Line;
- var x, y;
- var offset = 0;
- var Y, Cb, Cr, K, C, M, Ye, R, G, B;
- var colorTransform;
- var dataLength = width * height * this.components.length;
- var data = new Uint8Array(dataLength);
- switch (this.components.length) {
- case 1:
- component1 = this.components[0];
- for (y = 0; y < height; y++) {
- component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
- for (x = 0; x < width; x++) {
- Y = component1Line[0 | (x * component1.scaleX * scaleX)];
- data[offset++] = Y;
- }
- }
- break;
- case 2:
- // PDF might compress two component data in custom colorspace
- component1 = this.components[0];
- component2 = this.components[1];
- for (y = 0; y < height; y++) {
- component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
- component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
- for (x = 0; x < width; x++) {
- Y = component1Line[0 | (x * component1.scaleX * scaleX)];
- data[offset++] = Y;
- Y = component2Line[0 | (x * component2.scaleX * scaleX)];
- data[offset++] = Y;
- }
- }
- break;
- case 3:
- // The default transform for three components is true
- colorTransform = true;
- // The adobe transform marker overrides any previous setting
- if (this.adobe && this.adobe.transformCode)
- colorTransform = true;
- else if (typeof this.colorTransform !== 'undefined')
- colorTransform = !!this.colorTransform;
- component1 = this.components[0];
- component2 = this.components[1];
- component3 = this.components[2];
- for (y = 0; y < height; y++) {
- component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
- component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
- component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];
- for (x = 0; x < width; x++) {
- if (!colorTransform) {
- R = component1Line[0 | (x * component1.scaleX * scaleX)];
- G = component2Line[0 | (x * component2.scaleX * scaleX)];
- B = component3Line[0 | (x * component3.scaleX * scaleX)];
- } else {
- Y = component1Line[0 | (x * component1.scaleX * scaleX)];
- Cb = component2Line[0 | (x * component2.scaleX * scaleX)];
- Cr = component3Line[0 | (x * component3.scaleX * scaleX)];
- R = clampTo8bit(Y + 1.402 * (Cr - 128));
- G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
- B = clampTo8bit(Y + 1.772 * (Cb - 128));
- }
- data[offset++] = R;
- data[offset++] = G;
- data[offset++] = B;
- }
- }
- break;
- case 4:
- if (!this.adobe)
- throw 'Unsupported color mode (4 components)';
- // The default transform for four components is false
- colorTransform = false;
- // The adobe transform marker overrides any previous setting
- if (this.adobe && this.adobe.transformCode)
- colorTransform = true;
- else if (typeof this.colorTransform !== 'undefined')
- colorTransform = !!this.colorTransform;
- component1 = this.components[0];
- component2 = this.components[1];
- component3 = this.components[2];
- component4 = this.components[3];
- for (y = 0; y < height; y++) {
- component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];
- component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];
- component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];
- component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)];
- for (x = 0; x < width; x++) {
- if (!colorTransform) {
- C = component1Line[0 | (x * component1.scaleX * scaleX)];
- M = component2Line[0 | (x * component2.scaleX * scaleX)];
- Ye = component3Line[0 | (x * component3.scaleX * scaleX)];
- K = component4Line[0 | (x * component4.scaleX * scaleX)];
- } else {
- Y = component1Line[0 | (x * component1.scaleX * scaleX)];
- Cb = component2Line[0 | (x * component2.scaleX * scaleX)];
- Cr = component3Line[0 | (x * component3.scaleX * scaleX)];
- K = component4Line[0 | (x * component4.scaleX * scaleX)];
- C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));
- M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
- Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));
- }
- data[offset++] = 255-C;
- data[offset++] = 255-M;
- data[offset++] = 255-Ye;
- data[offset++] = 255-K;
- }
- }
- break;
- default:
- throw 'Unsupported color mode';
- }
- return data;
- },
- copyToImageData: function copyToImageData(imageData) {
- var width = imageData.width, height = imageData.height;
- var imageDataArray = imageData.data;
- var data = this.getData(width, height);
- var i = 0, j = 0, x, y;
- var Y, K, C, M, R, G, B;
- switch (this.components.length) {
- case 1:
- for (y = 0; y < height; y++) {
- for (x = 0; x < width; x++) {
- Y = data[i++];
- imageDataArray[j++] = Y;
- imageDataArray[j++] = Y;
- imageDataArray[j++] = Y;
- imageDataArray[j++] = 255;
- }
- }
- break;
- case 3:
- for (y = 0; y < height; y++) {
- for (x = 0; x < width; x++) {
- R = data[i++];
- G = data[i++];
- B = data[i++];
- imageDataArray[j++] = R;
- imageDataArray[j++] = G;
- imageDataArray[j++] = B;
- imageDataArray[j++] = 255;
- }
- }
- break;
- case 4:
- for (y = 0; y < height; y++) {
- for (x = 0; x < width; x++) {
- C = data[i++];
- M = data[i++];
- Y = data[i++];
- K = data[i++];
- R = 255 - clampTo8bit(C * (1 - K / 255) + K);
- G = 255 - clampTo8bit(M * (1 - K / 255) + K);
- B = 255 - clampTo8bit(Y * (1 - K / 255) + K);
- imageDataArray[j++] = R;
- imageDataArray[j++] = G;
- imageDataArray[j++] = B;
- imageDataArray[j++] = 255;
- }
- }
- break;
- default:
- throw 'Unsupported color mode';
- }
- }
- };
- return constructor;
- })();
- module.exports = decode;
- function decode(jpegData, useTArray) {
- var arr = new Uint8Array(jpegData);
- var decoder = new JpegImage();
- decoder.parse(arr);
- var image = {
- width: decoder.width,
- height: decoder.height,
- data: useTArray ?
- new Uint8Array(decoder.width * decoder.height * 4) :
- new Buffer(decoder.width * decoder.height * 4)
- };
- decoder.copyToImageData(image);
- return image;
- }
- }).call(this,require("buffer").Buffer)
- },{"buffer":47}],261:[function(require,module,exports){
- (function (Buffer){
- /*
- Copyright (c) 2008, Adobe Systems Incorporated
- All rights reserved.
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the name of Adobe Systems Incorporated nor the names of its
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- /*
- JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
- Basic GUI blocking jpeg encoder
- */
- var btoa = btoa || function(buf) {
- return new Buffer(buf).toString('base64');
- };
- function JPEGEncoder(quality) {
- var self = this;
- var fround = Math.round;
- var ffloor = Math.floor;
- var YTable = new Array(64);
- var UVTable = new Array(64);
- var fdtbl_Y = new Array(64);
- var fdtbl_UV = new Array(64);
- var YDC_HT;
- var UVDC_HT;
- var YAC_HT;
- var UVAC_HT;
-
- var bitcode = new Array(65535);
- var category = new Array(65535);
- var outputfDCTQuant = new Array(64);
- var DU = new Array(64);
- var byteout = [];
- var bytenew = 0;
- var bytepos = 7;
-
- var YDU = new Array(64);
- var UDU = new Array(64);
- var VDU = new Array(64);
- var clt = new Array(256);
- var RGB_YUV_TABLE = new Array(2048);
- var currentQuality;
-
- var ZigZag = [
- 0, 1, 5, 6,14,15,27,28,
- 2, 4, 7,13,16,26,29,42,
- 3, 8,12,17,25,30,41,43,
- 9,11,18,24,31,40,44,53,
- 10,19,23,32,39,45,52,54,
- 20,22,33,38,46,51,55,60,
- 21,34,37,47,50,56,59,61,
- 35,36,48,49,57,58,62,63
- ];
-
- var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
- var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
- var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
- var std_ac_luminance_values = [
- 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
- 0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
- 0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
- 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
- 0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
- 0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
- 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
- 0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
- 0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
- 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
- 0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
- 0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
- 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
- 0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
- 0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
- 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
- 0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
- 0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
- 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
- 0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
- 0xf9,0xfa
- ];
-
- var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
- var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
- var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
- var std_ac_chrominance_values = [
- 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
- 0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
- 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
- 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
- 0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
- 0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
- 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
- 0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
- 0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
- 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
- 0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
- 0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
- 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
- 0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
- 0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
- 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
- 0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
- 0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
- 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
- 0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
- 0xf9,0xfa
- ];
-
- function initQuantTables(sf){
- var YQT = [
- 16, 11, 10, 16, 24, 40, 51, 61,
- 12, 12, 14, 19, 26, 58, 60, 55,
- 14, 13, 16, 24, 40, 57, 69, 56,
- 14, 17, 22, 29, 51, 87, 80, 62,
- 18, 22, 37, 56, 68,109,103, 77,
- 24, 35, 55, 64, 81,104,113, 92,
- 49, 64, 78, 87,103,121,120,101,
- 72, 92, 95, 98,112,100,103, 99
- ];
-
- for (var i = 0; i < 64; i++) {
- var t = ffloor((YQT[i]*sf+50)/100);
- if (t < 1) {
- t = 1;
- } else if (t > 255) {
- t = 255;
- }
- YTable[ZigZag[i]] = t;
- }
- var UVQT = [
- 17, 18, 24, 47, 99, 99, 99, 99,
- 18, 21, 26, 66, 99, 99, 99, 99,
- 24, 26, 56, 99, 99, 99, 99, 99,
- 47, 66, 99, 99, 99, 99, 99, 99,
- 99, 99, 99, 99, 99, 99, 99, 99,
- 99, 99, 99, 99, 99, 99, 99, 99,
- 99, 99, 99, 99, 99, 99, 99, 99,
- 99, 99, 99, 99, 99, 99, 99, 99
- ];
- for (var j = 0; j < 64; j++) {
- var u = ffloor((UVQT[j]*sf+50)/100);
- if (u < 1) {
- u = 1;
- } else if (u > 255) {
- u = 255;
- }
- UVTable[ZigZag[j]] = u;
- }
- var aasf = [
- 1.0, 1.387039845, 1.306562965, 1.175875602,
- 1.0, 0.785694958, 0.541196100, 0.275899379
- ];
- var k = 0;
- for (var row = 0; row < 8; row++)
- {
- for (var col = 0; col < 8; col++)
- {
- fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
- fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
- k++;
- }
- }
- }
-
- function computeHuffmanTbl(nrcodes, std_table){
- var codevalue = 0;
- var pos_in_table = 0;
- var HT = new Array();
- for (var k = 1; k <= 16; k++) {
- for (var j = 1; j <= nrcodes[k]; j++) {
- HT[std_table[pos_in_table]] = [];
- HT[std_table[pos_in_table]][0] = codevalue;
- HT[std_table[pos_in_table]][1] = k;
- pos_in_table++;
- codevalue++;
- }
- codevalue*=2;
- }
- return HT;
- }
-
- function initHuffmanTbl()
- {
- YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
- UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
- YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
- UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
- }
-
- function initCategoryNumber()
- {
- var nrlower = 1;
- var nrupper = 2;
- for (var cat = 1; cat <= 15; cat++) {
- //Positive numbers
- for (var nr = nrlower; nr<nrupper; nr++) {
- category[32767+nr] = cat;
- bitcode[32767+nr] = [];
- bitcode[32767+nr][1] = cat;
- bitcode[32767+nr][0] = nr;
- }
- //Negative numbers
- for (var nrneg =-(nrupper-1); nrneg<=-nrlower; nrneg++) {
- category[32767+nrneg] = cat;
- bitcode[32767+nrneg] = [];
- bitcode[32767+nrneg][1] = cat;
- bitcode[32767+nrneg][0] = nrupper-1+nrneg;
- }
- nrlower <<= 1;
- nrupper <<= 1;
- }
- }
-
- function initRGBYUVTable() {
- for(var i = 0; i < 256;i++) {
- RGB_YUV_TABLE[i] = 19595 * i;
- RGB_YUV_TABLE[(i+ 256)>>0] = 38470 * i;
- RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
- RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
- RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
- RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
- RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
- RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
- }
- }
-
- // IO functions
- function writeBits(bs)
- {
- var value = bs[0];
- var posval = bs[1]-1;
- while ( posval >= 0 ) {
- if (value & (1 << posval) ) {
- bytenew |= (1 << bytepos);
- }
- posval--;
- bytepos--;
- if (bytepos < 0) {
- if (bytenew == 0xFF) {
- writeByte(0xFF);
- writeByte(0);
- }
- else {
- writeByte(bytenew);
- }
- bytepos=7;
- bytenew=0;
- }
- }
- }
-
- function writeByte(value)
- {
- //byteout.push(clt[value]); // write char directly instead of converting later
- byteout.push(value);
- }
-
- function writeWord(value)
- {
- writeByte((value>>8)&0xFF);
- writeByte((value )&0xFF);
- }
-
- // DCT & quantization core
- function fDCTQuant(data, fdtbl)
- {
- var d0, d1, d2, d3, d4, d5, d6, d7;
- /* Pass 1: process rows. */
- var dataOff=0;
- var i;
- var I8 = 8;
- var I64 = 64;
- for (i=0; i<I8; ++i)
- {
- d0 = data[dataOff];
- d1 = data[dataOff+1];
- d2 = data[dataOff+2];
- d3 = data[dataOff+3];
- d4 = data[dataOff+4];
- d5 = data[dataOff+5];
- d6 = data[dataOff+6];
- d7 = data[dataOff+7];
-
- var tmp0 = d0 + d7;
- var tmp7 = d0 - d7;
- var tmp1 = d1 + d6;
- var tmp6 = d1 - d6;
- var tmp2 = d2 + d5;
- var tmp5 = d2 - d5;
- var tmp3 = d3 + d4;
- var tmp4 = d3 - d4;
-
- /* Even part */
- var tmp10 = tmp0 + tmp3; /* phase 2 */
- var tmp13 = tmp0 - tmp3;
- var tmp11 = tmp1 + tmp2;
- var tmp12 = tmp1 - tmp2;
-
- data[dataOff] = tmp10 + tmp11; /* phase 3 */
- data[dataOff+4] = tmp10 - tmp11;
-
- var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
- data[dataOff+2] = tmp13 + z1; /* phase 5 */
- data[dataOff+6] = tmp13 - z1;
-
- /* Odd part */
- tmp10 = tmp4 + tmp5; /* phase 2 */
- tmp11 = tmp5 + tmp6;
- tmp12 = tmp6 + tmp7;
-
- /* The rotator is modified from fig 4-8 to avoid extra negations. */
- var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
- var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
- var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
- var z3 = tmp11 * 0.707106781; /* c4 */
-
- var z11 = tmp7 + z3; /* phase 5 */
- var z13 = tmp7 - z3;
-
- data[dataOff+5] = z13 + z2; /* phase 6 */
- data[dataOff+3] = z13 - z2;
- data[dataOff+1] = z11 + z4;
- data[dataOff+7] = z11 - z4;
-
- dataOff += 8; /* advance pointer to next row */
- }
-
- /* Pass 2: process columns. */
- dataOff = 0;
- for (i=0; i<I8; ++i)
- {
- d0 = data[dataOff];
- d1 = data[dataOff + 8];
- d2 = data[dataOff + 16];
- d3 = data[dataOff + 24];
- d4 = data[dataOff + 32];
- d5 = data[dataOff + 40];
- d6 = data[dataOff + 48];
- d7 = data[dataOff + 56];
-
- var tmp0p2 = d0 + d7;
- var tmp7p2 = d0 - d7;
- var tmp1p2 = d1 + d6;
- var tmp6p2 = d1 - d6;
- var tmp2p2 = d2 + d5;
- var tmp5p2 = d2 - d5;
- var tmp3p2 = d3 + d4;
- var tmp4p2 = d3 - d4;
-
- /* Even part */
- var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
- var tmp13p2 = tmp0p2 - tmp3p2;
- var tmp11p2 = tmp1p2 + tmp2p2;
- var tmp12p2 = tmp1p2 - tmp2p2;
-
- data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
- data[dataOff+32] = tmp10p2 - tmp11p2;
-
- var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
- data[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */
- data[dataOff+48] = tmp13p2 - z1p2;
-
- /* Odd part */
- tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
- tmp11p2 = tmp5p2 + tmp6p2;
- tmp12p2 = tmp6p2 + tmp7p2;
-
- /* The rotator is modified from fig 4-8 to avoid extra negations. */
- var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
- var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */
- var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
- var z3p2 = tmp11p2 * 0.707106781; /* c4 */
-
- var z11p2 = tmp7p2 + z3p2; /* phase 5 */
- var z13p2 = tmp7p2 - z3p2;
-
- data[dataOff+40] = z13p2 + z2p2; /* phase 6 */
- data[dataOff+24] = z13p2 - z2p2;
- data[dataOff+ 8] = z11p2 + z4p2;
- data[dataOff+56] = z11p2 - z4p2;
-
- dataOff++; /* advance pointer to next column */
- }
-
- // Quantize/descale the coefficients
- var fDCTQuant;
- for (i=0; i<I64; ++i)
- {
- // Apply the quantization and scaling factor & Round to nearest integer
- fDCTQuant = data[i]*fdtbl[i];
- outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
- //outputfDCTQuant[i] = fround(fDCTQuant);
- }
- return outputfDCTQuant;
- }
-
- function writeAPP0()
- {
- writeWord(0xFFE0); // marker
- writeWord(16); // length
- writeByte(0x4A); // J
- writeByte(0x46); // F
- writeByte(0x49); // I
- writeByte(0x46); // F
- writeByte(0); // = "JFIF",'\0'
- writeByte(1); // versionhi
- writeByte(1); // versionlo
- writeByte(0); // xyunits
- writeWord(1); // xdensity
- writeWord(1); // ydensity
- writeByte(0); // thumbnwidth
- writeByte(0); // thumbnheight
- }
-
- function writeSOF0(width, height)
- {
- writeWord(0xFFC0); // marker
- writeWord(17); // length, truecolor YUV JPG
- writeByte(8); // precision
- writeWord(height);
- writeWord(width);
- writeByte(3); // nrofcomponents
- writeByte(1); // IdY
- writeByte(0x11); // HVY
- writeByte(0); // QTY
- writeByte(2); // IdU
- writeByte(0x11); // HVU
- writeByte(1); // QTU
- writeByte(3); // IdV
- writeByte(0x11); // HVV
- writeByte(1); // QTV
- }
-
- function writeDQT()
- {
- writeWord(0xFFDB); // marker
- writeWord(132); // length
- writeByte(0);
- for (var i=0; i<64; i++) {
- writeByte(YTable[i]);
- }
- writeByte(1);
- for (var j=0; j<64; j++) {
- writeByte(UVTable[j]);
- }
- }
-
- function writeDHT()
- {
- writeWord(0xFFC4); // marker
- writeWord(0x01A2); // length
-
- writeByte(0); // HTYDCinfo
- for (var i=0; i<16; i++) {
- writeByte(std_dc_luminance_nrcodes[i+1]);
- }
- for (var j=0; j<=11; j++) {
- writeByte(std_dc_luminance_values[j]);
- }
-
- writeByte(0x10); // HTYACinfo
- for (var k=0; k<16; k++) {
- writeByte(std_ac_luminance_nrcodes[k+1]);
- }
- for (var l=0; l<=161; l++) {
- writeByte(std_ac_luminance_values[l]);
- }
-
- writeByte(1); // HTUDCinfo
- for (var m=0; m<16; m++) {
- writeByte(std_dc_chrominance_nrcodes[m+1]);
- }
- for (var n=0; n<=11; n++) {
- writeByte(std_dc_chrominance_values[n]);
- }
-
- writeByte(0x11); // HTUACinfo
- for (var o=0; o<16; o++) {
- writeByte(std_ac_chrominance_nrcodes[o+1]);
- }
- for (var p=0; p<=161; p++) {
- writeByte(std_ac_chrominance_values[p]);
- }
- }
-
- function writeSOS()
- {
- writeWord(0xFFDA); // marker
- writeWord(12); // length
- writeByte(3); // nrofcomponents
- writeByte(1); // IdY
- writeByte(0); // HTY
- writeByte(2); // IdU
- writeByte(0x11); // HTU
- writeByte(3); // IdV
- writeByte(0x11); // HTV
- writeByte(0); // Ss
- writeByte(0x3f); // Se
- writeByte(0); // Bf
- }
-
- function processDU(CDU, fdtbl, DC, HTDC, HTAC){
- var EOB = HTAC[0x00];
- var M16zeroes = HTAC[0xF0];
- var pos;
- var I16 = 16;
- var I63 = 63;
- var I64 = 64;
- var DU_DCT = fDCTQuant(CDU, fdtbl);
- //ZigZag reorder
- for (var j=0;j<I64;++j) {
- DU[ZigZag[j]]=DU_DCT[j];
- }
- var Diff = DU[0] - DC; DC = DU[0];
- //Encode DC
- if (Diff==0) {
- writeBits(HTDC[0]); // Diff might be 0
- } else {
- pos = 32767+Diff;
- writeBits(HTDC[category[pos]]);
- writeBits(bitcode[pos]);
- }
- //Encode ACs
- var end0pos = 63; // was const... which is crazy
- for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) {};
- //end0pos = first element in reverse order !=0
- if ( end0pos == 0) {
- writeBits(EOB);
- return DC;
- }
- var i = 1;
- var lng;
- while ( i <= end0pos ) {
- var startpos = i;
- for (; (DU[i]==0) && (i<=end0pos); ++i) {}
- var nrzeroes = i-startpos;
- if ( nrzeroes >= I16 ) {
- lng = nrzeroes>>4;
- for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
- writeBits(M16zeroes);
- nrzeroes = nrzeroes&0xF;
- }
- pos = 32767+DU[i];
- writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
- writeBits(bitcode[pos]);
- i++;
- }
- if ( end0pos != I63 ) {
- writeBits(EOB);
- }
- return DC;
- }
- function initCharLookupTable(){
- var sfcc = String.fromCharCode;
- for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
- clt[i] = sfcc(i);
- }
- }
-
- this.encode = function(image,quality) // image data object
- {
- var time_start = new Date().getTime();
-
- if(quality) setQuality(quality);
-
- // Initialize bit writer
- byteout = new Array();
- bytenew=0;
- bytepos=7;
-
- // Add JPEG headers
- writeWord(0xFFD8); // SOI
- writeAPP0();
- writeDQT();
- writeSOF0(image.width,image.height);
- writeDHT();
- writeSOS();
-
- // Encode 8x8 macroblocks
- var DCY=0;
- var DCU=0;
- var DCV=0;
-
- bytenew=0;
- bytepos=7;
-
-
- this.encode.displayName = "_encode_";
- var imageData = image.data;
- var width = image.width;
- var height = image.height;
- var quadWidth = width*4;
- var tripleWidth = width*3;
-
- var x, y = 0;
- var r, g, b;
- var start,p, col,row,pos;
- while(y < height){
- x = 0;
- while(x < quadWidth){
- start = quadWidth * y + x;
- p = start;
- col = -1;
- row = 0;
-
- for(pos=0; pos < 64; pos++){
- row = pos >> 3;// /8
- col = ( pos & 7 ) * 4; // %8
- p = start + ( row * quadWidth ) + col;
-
- if(y+row >= height){ // padding bottom
- p-= (quadWidth*(y+1+row-height));
- }
- if(x+col >= quadWidth){ // padding right
- p-= ((x+col) - quadWidth +4)
- }
-
- r = imageData[ p++ ];
- g = imageData[ p++ ];
- b = imageData[ p++ ];
-
-
- /* // calculate YUV values dynamically
- YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
- UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
- VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
- */
-
- // use lookup table (slightly faster)
- YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
- UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
- VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
- }
-
- DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
- DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
- DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
- x+=32;
- }
- y+=8;
- }
-
-
- ////////////////////////////////////////////////////////////////
-
- // Do the bit alignment of the EOI marker
- if ( bytepos >= 0 ) {
- var fillbits = [];
- fillbits[1] = bytepos+1;
- fillbits[0] = (1<<(bytepos+1))-1;
- writeBits(fillbits);
- }
-
- writeWord(0xFFD9); //EOI
- //return new Uint8Array(byteout);
- return new Buffer(byteout);
- var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
-
- byteout = [];
-
- // benchmarking
- var duration = new Date().getTime() - time_start;
- //console.log('Encoding time: '+ duration + 'ms');
- //
-
- return jpegDataUri
- }
-
- function setQuality(quality){
- if (quality <= 0) {
- quality = 1;
- }
- if (quality > 100) {
- quality = 100;
- }
-
- if(currentQuality == quality) return // don't recalc if unchanged
-
- var sf = 0;
- if (quality < 50) {
- sf = Math.floor(5000 / quality);
- } else {
- sf = Math.floor(200 - quality*2);
- }
-
- initQuantTables(sf);
- currentQuality = quality;
- //console.log('Quality set to: '+quality +'%');
- }
-
- function init(){
- var time_start = new Date().getTime();
- if(!quality) quality = 50;
- // Create tables
- initCharLookupTable()
- initHuffmanTbl();
- initCategoryNumber();
- initRGBYUVTable();
-
- setQuality(quality);
- var duration = new Date().getTime() - time_start;
- //console.log('Initialization '+ duration + 'ms');
- }
-
- init();
-
- };
- module.exports = encode;
- function encode(imgData, qu) {
- if (typeof qu === 'undefined') qu = 50;
- var encoder = new JPEGEncoder(qu);
- var data = encoder.encode(imgData, qu);
- return {
- data: data,
- width: imgData.width,
- height: imgData.height
- };
- }
- // helper function to get the imageData of an existing image on the current page.
- function getImageDataFromImage(idOrElement){
- var theImg = (typeof(idOrElement)=='string')? document.getElementById(idOrElement):idOrElement;
- var cvs = document.createElement('canvas');
- cvs.width = theImg.width;
- cvs.height = theImg.height;
- var ctx = cvs.getContext("2d");
- ctx.drawImage(theImg,0,0);
-
- return (ctx.getImageData(0, 0, cvs.width, cvs.height));
- }
- }).call(this,require("buffer").Buffer)
- },{"buffer":47}],262:[function(require,module,exports){
- (function (process){
- var path = require('path');
- var fs = require('fs');
- var _0777 = parseInt('0777', 8);
- module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
- function mkdirP (p, opts, f, made) {
- if (typeof opts === 'function') {
- f = opts;
- opts = {};
- }
- else if (!opts || typeof opts !== 'object') {
- opts = { mode: opts };
- }
-
- var mode = opts.mode;
- var xfs = opts.fs || fs;
-
- if (mode === undefined) {
- mode = _0777 & (~process.umask());
- }
- if (!made) made = null;
-
- var cb = f || function () {};
- p = path.resolve(p);
-
- xfs.mkdir(p, mode, function (er) {
- if (!er) {
- made = made || p;
- return cb(null, made);
- }
- switch (er.code) {
- case 'ENOENT':
- mkdirP(path.dirname(p), opts, function (er, made) {
- if (er) cb(er, made);
- else mkdirP(p, opts, cb, made);
- });
- break;
- // In the case of any other error, just see if there's a dir
- // there already. If so, then hooray! If not, then something
- // is borked.
- default:
- xfs.stat(p, function (er2, stat) {
- // if the stat fails, then that's super weird.
- // let the original error be the failure reason.
- if (er2 || !stat.isDirectory()) cb(er, made)
- else cb(null, made);
- });
- break;
- }
- });
- }
- mkdirP.sync = function sync (p, opts, made) {
- if (!opts || typeof opts !== 'object') {
- opts = { mode: opts };
- }
-
- var mode = opts.mode;
- var xfs = opts.fs || fs;
-
- if (mode === undefined) {
- mode = _0777 & (~process.umask());
- }
- if (!made) made = null;
- p = path.resolve(p);
- try {
- xfs.mkdirSync(p, mode);
- made = made || p;
- }
- catch (err0) {
- switch (err0.code) {
- case 'ENOENT' :
- made = sync(path.dirname(p), opts, made);
- sync(p, opts, made);
- break;
- // In the case of any other error, just see if there's a dir
- // there already. If so, then hooray! If not, then something
- // is borked.
- default:
- var stat;
- try {
- stat = xfs.statSync(p);
- }
- catch (err1) {
- throw err0;
- }
- if (!stat.isDirectory()) throw err0;
- break;
- }
- }
- return made;
- };
- }).call(this,require('_process'))
- },{"_process":312,"fs":46,"path":286}],263:[function(require,module,exports){
- /*
- object-assign
- (c) Sindre Sorhus
- @license MIT
- */
- 'use strict';
- /* eslint-disable no-unused-vars */
- var getOwnPropertySymbols = Object.getOwnPropertySymbols;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var propIsEnumerable = Object.prototype.propertyIsEnumerable;
- function toObject(val) {
- if (val === null || val === undefined) {
- throw new TypeError('Object.assign cannot be called with null or undefined');
- }
- return Object(val);
- }
- function shouldUseNative() {
- try {
- if (!Object.assign) {
- return false;
- }
- // Detect buggy property enumeration order in older V8 versions.
- // https://bugs.chromium.org/p/v8/issues/detail?id=4118
- var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
- test1[5] = 'de';
- if (Object.getOwnPropertyNames(test1)[0] === '5') {
- return false;
- }
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test2 = {};
- for (var i = 0; i < 10; i++) {
- test2['_' + String.fromCharCode(i)] = i;
- }
- var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
- return test2[n];
- });
- if (order2.join('') !== '0123456789') {
- return false;
- }
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test3 = {};
- 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
- test3[letter] = letter;
- });
- if (Object.keys(Object.assign({}, test3)).join('') !==
- 'abcdefghijklmnopqrst') {
- return false;
- }
- return true;
- } catch (err) {
- // We don't expect any of the above to throw, but better to be safe.
- return false;
- }
- }
- module.exports = shouldUseNative() ? Object.assign : function (target, source) {
- var from;
- var to = toObject(target);
- var symbols;
- for (var s = 1; s < arguments.length; s++) {
- from = Object(arguments[s]);
- for (var key in from) {
- if (hasOwnProperty.call(from, key)) {
- to[key] = from[key];
- }
- }
- if (getOwnPropertySymbols) {
- symbols = getOwnPropertySymbols(from);
- for (var i = 0; i < symbols.length; i++) {
- if (propIsEnumerable.call(from, symbols[i])) {
- to[symbols[i]] = from[symbols[i]];
- }
- }
- }
- }
- return to;
- };
- },{}],264:[function(require,module,exports){
- // (c) Dean McNamee <dean@gmail.com>, 2013.
- //
- // https://github.com/deanm/omggif
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to
- // deal in the Software without restriction, including without limitation the
- // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- // sell copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
- // IN THE SOFTWARE.
- //
- // omggif is a JavaScript implementation of a GIF 89a encoder and decoder,
- // including animation and compression. It does not rely on any specific
- // underlying system, so should run in the browser, Node, or Plask.
- "use strict";
- function GifWriter(buf, width, height, gopts) {
- var p = 0;
- var gopts = gopts === undefined ? { } : gopts;
- var loop_count = gopts.loop === undefined ? null : gopts.loop;
- var global_palette = gopts.palette === undefined ? null : gopts.palette;
- if (width <= 0 || height <= 0 || width > 65535 || height > 65535)
- throw new Error("Width/Height invalid.");
- function check_palette_and_num_colors(palette) {
- var num_colors = palette.length;
- if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1)) {
- throw new Error(
- "Invalid code/color length, must be power of 2 and 2 .. 256.");
- }
- return num_colors;
- }
- // - Header.
- buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF
- buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a
- // Handling of Global Color Table (palette) and background index.
- var gp_num_colors_pow2 = 0;
- var background = 0;
- if (global_palette !== null) {
- var gp_num_colors = check_palette_and_num_colors(global_palette);
- while (gp_num_colors >>= 1) ++gp_num_colors_pow2;
- gp_num_colors = 1 << gp_num_colors_pow2;
- --gp_num_colors_pow2;
- if (gopts.background !== undefined) {
- background = gopts.background;
- if (background >= gp_num_colors)
- throw new Error("Background index out of range.");
- // The GIF spec states that a background index of 0 should be ignored, so
- // this is probably a mistake and you really want to set it to another
- // slot in the palette. But actually in the end most browsers, etc end
- // up ignoring this almost completely (including for dispose background).
- if (background === 0)
- throw new Error("Background index explicitly passed as 0.");
- }
- }
- // - Logical Screen Descriptor.
- // NOTE(deanm): w/h apparently ignored by implementations, but set anyway.
- buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff;
- buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff;
- // NOTE: Indicates 0-bpp original color resolution (unused?).
- buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag.
- gp_num_colors_pow2; // NOTE: No sort flag (unused?).
- buf[p++] = background; // Background Color Index.
- buf[p++] = 0; // Pixel aspect ratio (unused?).
- // - Global Color Table
- if (global_palette !== null) {
- for (var i = 0, il = global_palette.length; i < il; ++i) {
- var rgb = global_palette[i];
- buf[p++] = rgb >> 16 & 0xff;
- buf[p++] = rgb >> 8 & 0xff;
- buf[p++] = rgb & 0xff;
- }
- }
- if (loop_count !== null) { // Netscape block for looping.
- if (loop_count < 0 || loop_count > 65535)
- throw new Error("Loop count invalid.")
- // Extension code, label, and length.
- buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b;
- // NETSCAPE2.0
- buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53;
- buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45;
- buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30;
- // Sub-block
- buf[p++] = 0x03; buf[p++] = 0x01;
- buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff;
- buf[p++] = 0x00; // Terminator.
- }
- var ended = false;
- this.addFrame = function(x, y, w, h, indexed_pixels, opts) {
- if (ended === true) { --p; ended = false; } // Un-end.
- opts = opts === undefined ? { } : opts;
- // TODO(deanm): Bounds check x, y. Do they need to be within the virtual
- // canvas width/height, I imagine?
- if (x < 0 || y < 0 || x > 65535 || y > 65535)
- throw new Error("x/y invalid.")
- if (w <= 0 || h <= 0 || w > 65535 || h > 65535)
- throw new Error("Width/Height invalid.")
- if (indexed_pixels.length < w * h)
- throw new Error("Not enough pixels for the frame size.");
- var using_local_palette = true;
- var palette = opts.palette;
- if (palette === undefined || palette === null) {
- using_local_palette = false;
- palette = global_palette;
- }
- if (palette === undefined || palette === null)
- throw new Error("Must supply either a local or global palette.");
- var num_colors = check_palette_and_num_colors(palette);
- // Compute the min_code_size (power of 2), destroying num_colors.
- var min_code_size = 0;
- while (num_colors >>= 1) ++min_code_size;
- num_colors = 1 << min_code_size; // Now we can easily get it back.
- var delay = opts.delay === undefined ? 0 : opts.delay;
- // From the spec:
- // 0 - No disposal specified. The decoder is
- // not required to take any action.
- // 1 - Do not dispose. The graphic is to be left
- // in place.
- // 2 - Restore to background color. The area used by the
- // graphic must be restored to the background color.
- // 3 - Restore to previous. The decoder is required to
- // restore the area overwritten by the graphic with
- // what was there prior to rendering the graphic.
- // 4-7 - To be defined.
- // NOTE(deanm): Dispose background doesn't really work, apparently most
- // browsers ignore the background palette index and clear to transparency.
- var disposal = opts.disposal === undefined ? 0 : opts.disposal;
- if (disposal < 0 || disposal > 3) // 4-7 is reserved.
- throw new Error("Disposal out of range.");
- var use_transparency = false;
- var transparent_index = 0;
- if (opts.transparent !== undefined && opts.transparent !== null) {
- use_transparency = true;
- transparent_index = opts.transparent;
- if (transparent_index < 0 || transparent_index >= num_colors)
- throw new Error("Transparent color index.");
- }
- if (disposal !== 0 || use_transparency || delay !== 0) {
- // - Graphics Control Extension
- buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label.
- buf[p++] = 4; // Byte size.
- buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0);
- buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff;
- buf[p++] = transparent_index; // Transparent color index.
- buf[p++] = 0; // Block Terminator.
- }
- // - Image Descriptor
- buf[p++] = 0x2c; // Image Seperator.
- buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left.
- buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top.
- buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff;
- buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff;
- // NOTE: No sort flag (unused?).
- // TODO(deanm): Support interlace.
- buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0;
- // - Local Color Table
- if (using_local_palette === true) {
- for (var i = 0, il = palette.length; i < il; ++i) {
- var rgb = palette[i];
- buf[p++] = rgb >> 16 & 0xff;
- buf[p++] = rgb >> 8 & 0xff;
- buf[p++] = rgb & 0xff;
- }
- }
- p = GifWriterOutputLZWCodeStream(
- buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);
- return p;
- };
- this.end = function() {
- if (ended === false) {
- buf[p++] = 0x3b; // Trailer.
- ended = true;
- }
- return p;
- };
- this.getOutputBuffer = function() { return buf; };
- this.setOutputBuffer = function(v) { buf = v; };
- this.getOutputBufferPosition = function() { return p; };
- this.setOutputBufferPosition = function(v) { p = v; };
- }
- // Main compression routine, palette indexes -> LZW code stream.
- // |index_stream| must have at least one entry.
- function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {
- buf[p++] = min_code_size;
- var cur_subblock = p++; // Pointing at the length field.
- var clear_code = 1 << min_code_size;
- var code_mask = clear_code - 1;
- var eoi_code = clear_code + 1;
- var next_code = eoi_code + 1;
- var cur_code_size = min_code_size + 1; // Number of bits per code.
- var cur_shift = 0;
- // We have at most 12-bit codes, so we should have to hold a max of 19
- // bits here (and then we would write out).
- var cur = 0;
- function emit_bytes_to_buffer(bit_block_size) {
- while (cur_shift >= bit_block_size) {
- buf[p++] = cur & 0xff;
- cur >>= 8; cur_shift -= 8;
- if (p === cur_subblock + 256) { // Finished a subblock.
- buf[cur_subblock] = 255;
- cur_subblock = p++;
- }
- }
- }
- function emit_code(c) {
- cur |= c << cur_shift;
- cur_shift += cur_code_size;
- emit_bytes_to_buffer(8);
- }
- // I am not an expert on the topic, and I don't want to write a thesis.
- // However, it is good to outline here the basic algorithm and the few data
- // structures and optimizations here that make this implementation fast.
- // The basic idea behind LZW is to build a table of previously seen runs
- // addressed by a short id (herein called output code). All data is
- // referenced by a code, which represents one or more values from the
- // original input stream. All input bytes can be referenced as the same
- // value as an output code. So if you didn't want any compression, you
- // could more or less just output the original bytes as codes (there are
- // some details to this, but it is the idea). In order to achieve
- // compression, values greater then the input range (codes can be up to
- // 12-bit while input only 8-bit) represent a sequence of previously seen
- // inputs. The decompressor is able to build the same mapping while
- // decoding, so there is always a shared common knowledge between the
- // encoding and decoder, which is also important for "timing" aspects like
- // how to handle variable bit width code encoding.
- //
- // One obvious but very important consequence of the table system is there
- // is always a unique id (at most 12-bits) to map the runs. 'A' might be
- // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship
- // can be used for an effecient lookup strategy for the code mapping. We
- // need to know if a run has been seen before, and be able to map that run
- // to the output code. Since we start with known unique ids (input bytes),
- // and then from those build more unique ids (table entries), we can
- // continue this chain (almost like a linked list) to always have small
- // integer values that represent the current byte chains in the encoder.
- // This means instead of tracking the input bytes (AAAABCD) to know our
- // current state, we can track the table entry for AAAABC (it is guaranteed
- // to exist by the nature of the algorithm) and the next character D.
- // Therefor the tuple of (table_entry, byte) is guaranteed to also be
- // unique. This allows us to create a simple lookup key for mapping input
- // sequences to codes (table indices) without having to store or search
- // any of the code sequences. So if 'AAAA' has a table entry of 12, the
- // tuple of ('AAAA', K) for any input byte K will be unique, and can be our
- // key. This leads to a integer value at most 20-bits, which can always
- // fit in an SMI value and be used as a fast sparse array / object key.
- // Output code for the current contents of the index buffer.
- var ib_code = index_stream[0] & code_mask; // Load first input index.
- var code_table = { }; // Key'd on our 20-bit "tuple".
- emit_code(clear_code); // Spec says first code should be a clear code.
- // First index already loaded, process the rest of the stream.
- for (var i = 1, il = index_stream.length; i < il; ++i) {
- var k = index_stream[i] & code_mask;
- var cur_key = ib_code << 8 | k; // (prev, k) unique tuple.
- var cur_code = code_table[cur_key]; // buffer + k.
- // Check if we have to create a new code table entry.
- if (cur_code === undefined) { // We don't have buffer + k.
- // Emit index buffer (without k).
- // This is an inline version of emit_code, because this is the core
- // writing routine of the compressor (and V8 cannot inline emit_code
- // because it is a closure here in a different context). Additionally
- // we can call emit_byte_to_buffer less often, because we can have
- // 30-bits (from our 31-bit signed SMI), and we know our codes will only
- // be 12-bits, so can safely have 18-bits there without overflow.
- // emit_code(ib_code);
- cur |= ib_code << cur_shift;
- cur_shift += cur_code_size;
- while (cur_shift >= 8) {
- buf[p++] = cur & 0xff;
- cur >>= 8; cur_shift -= 8;
- if (p === cur_subblock + 256) { // Finished a subblock.
- buf[cur_subblock] = 255;
- cur_subblock = p++;
- }
- }
- if (next_code === 4096) { // Table full, need a clear.
- emit_code(clear_code);
- next_code = eoi_code + 1;
- cur_code_size = min_code_size + 1;
- code_table = { };
- } else { // Table not full, insert a new entry.
- // Increase our variable bit code sizes if necessary. This is a bit
- // tricky as it is based on "timing" between the encoding and
- // decoder. From the encoders perspective this should happen after
- // we've already emitted the index buffer and are about to create the
- // first table entry that would overflow our current code bit size.
- if (next_code >= (1 << cur_code_size)) ++cur_code_size;
- code_table[cur_key] = next_code++; // Insert into code table.
- }
- ib_code = k; // Index buffer to single input k.
- } else {
- ib_code = cur_code; // Index buffer to sequence in code table.
- }
- }
- emit_code(ib_code); // There will still be something in the index buffer.
- emit_code(eoi_code); // End Of Information.
- // Flush / finalize the sub-blocks stream to the buffer.
- emit_bytes_to_buffer(1);
- // Finish the sub-blocks, writing out any unfinished lengths and
- // terminating with a sub-block of length 0. If we have already started
- // but not yet used a sub-block it can just become the terminator.
- if (cur_subblock + 1 === p) { // Started but unused.
- buf[cur_subblock] = 0;
- } else { // Started and used, write length and additional terminator block.
- buf[cur_subblock] = p - cur_subblock - 1;
- buf[p++] = 0;
- }
- return p;
- }
- function GifReader(buf) {
- var p = 0;
- // - Header (GIF87a or GIF89a).
- if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 ||
- buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) {
- throw new Error("Invalid GIF 87a/89a header.");
- }
- // - Logical Screen Descriptor.
- var width = buf[p++] | buf[p++] << 8;
- var height = buf[p++] | buf[p++] << 8;
- var pf0 = buf[p++]; // <Packed Fields>.
- var global_palette_flag = pf0 >> 7;
- var num_global_colors_pow2 = pf0 & 0x7;
- var num_global_colors = 1 << (num_global_colors_pow2 + 1);
- var background = buf[p++];
- buf[p++]; // Pixel aspect ratio (unused?).
- var global_palette_offset = null;
- var global_palette_size = null;
- if (global_palette_flag) {
- global_palette_offset = p;
- global_palette_size = num_global_colors;
- p += num_global_colors * 3; // Seek past palette.
- }
- var no_eof = true;
- var frames = [ ];
- var delay = 0;
- var transparent_index = null;
- var disposal = 0; // 0 - No disposal specified.
- var loop_count = null;
- this.width = width;
- this.height = height;
- while (no_eof && p < buf.length) {
- switch (buf[p++]) {
- case 0x21: // Graphics Control Extension Block
- switch (buf[p++]) {
- case 0xff: // Application specific block
- // Try if it's a Netscape block (with animation loop counter).
- if (buf[p ] !== 0x0b || // 21 FF already read, check block size.
- // NETSCAPE2.0
- buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 &&
- buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 &&
- buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 &&
- buf[p+10] == 0x2e && buf[p+11] == 0x30 &&
- // Sub-block
- buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) {
- p += 14;
- loop_count = buf[p++] | buf[p++] << 8;
- p++; // Skip terminator.
- } else { // We don't know what it is, just try to get past it.
- p += 12;
- while (true) { // Seek through subblocks.
- var block_size = buf[p++];
- // Bad block size (ex: undefined from an out of bounds read).
- if (!(block_size >= 0)) throw Error("Invalid block size");
- if (block_size === 0) break; // 0 size is terminator
- p += block_size;
- }
- }
- break;
- case 0xf9: // Graphics Control Extension
- if (buf[p++] !== 0x4 || buf[p+4] !== 0)
- throw new Error("Invalid graphics extension block.");
- var pf1 = buf[p++];
- delay = buf[p++] | buf[p++] << 8;
- transparent_index = buf[p++];
- if ((pf1 & 1) === 0) transparent_index = null;
- disposal = pf1 >> 2 & 0x7;
- p++; // Skip terminator.
- break;
- case 0xfe: // Comment Extension.
- while (true) { // Seek through subblocks.
- var block_size = buf[p++];
- // Bad block size (ex: undefined from an out of bounds read).
- if (!(block_size >= 0)) throw Error("Invalid block size");
- if (block_size === 0) break; // 0 size is terminator
- // console.log(buf.slice(p, p+block_size).toString('ascii'));
- p += block_size;
- }
- break;
- default:
- throw new Error(
- "Unknown graphic control label: 0x" + buf[p-1].toString(16));
- }
- break;
- case 0x2c: // Image Descriptor.
- var x = buf[p++] | buf[p++] << 8;
- var y = buf[p++] | buf[p++] << 8;
- var w = buf[p++] | buf[p++] << 8;
- var h = buf[p++] | buf[p++] << 8;
- var pf2 = buf[p++];
- var local_palette_flag = pf2 >> 7;
- var interlace_flag = pf2 >> 6 & 1;
- var num_local_colors_pow2 = pf2 & 0x7;
- var num_local_colors = 1 << (num_local_colors_pow2 + 1);
- var palette_offset = global_palette_offset;
- var palette_size = global_palette_size;
- var has_local_palette = false;
- if (local_palette_flag) {
- var has_local_palette = true;
- palette_offset = p; // Override with local palette.
- palette_size = num_local_colors;
- p += num_local_colors * 3; // Seek past palette.
- }
- var data_offset = p;
- p++; // codesize
- while (true) {
- var block_size = buf[p++];
- // Bad block size (ex: undefined from an out of bounds read).
- if (!(block_size >= 0)) throw Error("Invalid block size");
- if (block_size === 0) break; // 0 size is terminator
- p += block_size;
- }
- frames.push({x: x, y: y, width: w, height: h,
- has_local_palette: has_local_palette,
- palette_offset: palette_offset,
- palette_size: palette_size,
- data_offset: data_offset,
- data_length: p - data_offset,
- transparent_index: transparent_index,
- interlaced: !!interlace_flag,
- delay: delay,
- disposal: disposal});
- break;
- case 0x3b: // Trailer Marker (end of file).
- no_eof = false;
- break;
- default:
- throw new Error("Unknown gif block: 0x" + buf[p-1].toString(16));
- break;
- }
- }
- this.numFrames = function() {
- return frames.length;
- };
- this.loopCount = function() {
- return loop_count;
- };
- this.frameInfo = function(frame_num) {
- if (frame_num < 0 || frame_num >= frames.length)
- throw new Error("Frame index out of range.");
- return frames[frame_num];
- }
- this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {
- var frame = this.frameInfo(frame_num);
- var num_pixels = frame.width * frame.height;
- var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
- GifReaderLZWOutputIndexStream(
- buf, frame.data_offset, index_stream, num_pixels);
- var palette_offset = frame.palette_offset;
- // NOTE(deanm): It seems to be much faster to compare index to 256 than
- // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
- // the profile, not sure if it's related to using a Uint8Array.
- var trans = frame.transparent_index;
- if (trans === null) trans = 256;
- // We are possibly just blitting to a portion of the entire frame.
- // That is a subrect within the framerect, so the additional pixels
- // must be skipped over after we finished a scanline.
- var framewidth = frame.width;
- var framestride = width - framewidth;
- var xleft = framewidth; // Number of subrect pixels left in scanline.
- // Output indicies of the top left and bottom right corners of the subrect.
- var opbeg = ((frame.y * width) + frame.x) * 4;
- var opend = ((frame.y + frame.height) * width + frame.x) * 4;
- var op = opbeg;
- var scanstride = framestride * 4;
- // Use scanstride to skip past the rows when interlacing. This is skipping
- // 7 rows for the first two passes, then 3 then 1.
- if (frame.interlaced === true) {
- scanstride += width * 4 * 7; // Pass 1.
- }
- var interlaceskip = 8; // Tracking the row interval in the current pass.
- for (var i = 0, il = index_stream.length; i < il; ++i) {
- var index = index_stream[i];
- if (xleft === 0) { // Beginning of new scan line
- op += scanstride;
- xleft = framewidth;
- if (op >= opend) { // Catch the wrap to switch passes when interlacing.
- scanstride = framestride * 4 + width * 4 * (interlaceskip-1);
- // interlaceskip / 2 * 4 is interlaceskip << 1.
- op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
- interlaceskip >>= 1;
- }
- }
- if (index === trans) {
- op += 4;
- } else {
- var r = buf[palette_offset + index * 3];
- var g = buf[palette_offset + index * 3 + 1];
- var b = buf[palette_offset + index * 3 + 2];
- pixels[op++] = b;
- pixels[op++] = g;
- pixels[op++] = r;
- pixels[op++] = 255;
- }
- --xleft;
- }
- };
- // I will go to copy and paste hell one day...
- this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {
- var frame = this.frameInfo(frame_num);
- var num_pixels = frame.width * frame.height;
- var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
- GifReaderLZWOutputIndexStream(
- buf, frame.data_offset, index_stream, num_pixels);
- var palette_offset = frame.palette_offset;
- // NOTE(deanm): It seems to be much faster to compare index to 256 than
- // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
- // the profile, not sure if it's related to using a Uint8Array.
- var trans = frame.transparent_index;
- if (trans === null) trans = 256;
- // We are possibly just blitting to a portion of the entire frame.
- // That is a subrect within the framerect, so the additional pixels
- // must be skipped over after we finished a scanline.
- var framewidth = frame.width;
- var framestride = width - framewidth;
- var xleft = framewidth; // Number of subrect pixels left in scanline.
- // Output indicies of the top left and bottom right corners of the subrect.
- var opbeg = ((frame.y * width) + frame.x) * 4;
- var opend = ((frame.y + frame.height) * width + frame.x) * 4;
- var op = opbeg;
- var scanstride = framestride * 4;
- // Use scanstride to skip past the rows when interlacing. This is skipping
- // 7 rows for the first two passes, then 3 then 1.
- if (frame.interlaced === true) {
- scanstride += width * 4 * 7; // Pass 1.
- }
- var interlaceskip = 8; // Tracking the row interval in the current pass.
- for (var i = 0, il = index_stream.length; i < il; ++i) {
- var index = index_stream[i];
- if (xleft === 0) { // Beginning of new scan line
- op += scanstride;
- xleft = framewidth;
- if (op >= opend) { // Catch the wrap to switch passes when interlacing.
- scanstride = framestride * 4 + width * 4 * (interlaceskip-1);
- // interlaceskip / 2 * 4 is interlaceskip << 1.
- op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
- interlaceskip >>= 1;
- }
- }
- if (index === trans) {
- op += 4;
- } else {
- var r = buf[palette_offset + index * 3];
- var g = buf[palette_offset + index * 3 + 1];
- var b = buf[palette_offset + index * 3 + 2];
- pixels[op++] = r;
- pixels[op++] = g;
- pixels[op++] = b;
- pixels[op++] = 255;
- }
- --xleft;
- }
- };
- }
- function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {
- var min_code_size = code_stream[p++];
- var clear_code = 1 << min_code_size;
- var eoi_code = clear_code + 1;
- var next_code = eoi_code + 1;
- var cur_code_size = min_code_size + 1; // Number of bits per code.
- // NOTE: This shares the same name as the encoder, but has a different
- // meaning here. Here this masks each code coming from the code stream.
- var code_mask = (1 << cur_code_size) - 1;
- var cur_shift = 0;
- var cur = 0;
- var op = 0; // Output pointer.
- var subblock_size = code_stream[p++];
- // TODO(deanm): Would using a TypedArray be any faster? At least it would
- // solve the fast mode / backing store uncertainty.
- // var code_table = Array(4096);
- var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.
- var prev_code = null; // Track code-1.
- while (true) {
- // Read up to two bytes, making sure we always 12-bits for max sized code.
- while (cur_shift < 16) {
- if (subblock_size === 0) break; // No more data to be read.
- cur |= code_stream[p++] << cur_shift;
- cur_shift += 8;
- if (subblock_size === 1) { // Never let it get to 0 to hold logic above.
- subblock_size = code_stream[p++]; // Next subblock.
- } else {
- --subblock_size;
- }
- }
- // TODO(deanm): We should never really get here, we should have received
- // and EOI.
- if (cur_shift < cur_code_size)
- break;
- var code = cur & code_mask;
- cur >>= cur_code_size;
- cur_shift -= cur_code_size;
- // TODO(deanm): Maybe should check that the first code was a clear code,
- // at least this is what you're supposed to do. But actually our encoder
- // now doesn't emit a clear code first anyway.
- if (code === clear_code) {
- // We don't actually have to clear the table. This could be a good idea
- // for greater error checking, but we don't really do any anyway. We
- // will just track it with next_code and overwrite old entries.
- next_code = eoi_code + 1;
- cur_code_size = min_code_size + 1;
- code_mask = (1 << cur_code_size) - 1;
- // Don't update prev_code ?
- prev_code = null;
- continue;
- } else if (code === eoi_code) {
- break;
- }
- // We have a similar situation as the decoder, where we want to store
- // variable length entries (code table entries), but we want to do in a
- // faster manner than an array of arrays. The code below stores sort of a
- // linked list within the code table, and then "chases" through it to
- // construct the dictionary entries. When a new entry is created, just the
- // last byte is stored, and the rest (prefix) of the entry is only
- // referenced by its table entry. Then the code chases through the
- // prefixes until it reaches a single byte code. We have to chase twice,
- // first to compute the length, and then to actually copy the data to the
- // output (backwards, since we know the length). The alternative would be
- // storing something in an intermediate stack, but that doesn't make any
- // more sense. I implemented an approach where it also stored the length
- // in the code table, although it's a bit tricky because you run out of
- // bits (12 + 12 + 8), but I didn't measure much improvements (the table
- // entries are generally not the long). Even when I created benchmarks for
- // very long table entries the complexity did not seem worth it.
- // The code table stores the prefix entry in 12 bits and then the suffix
- // byte in 8 bits, so each entry is 20 bits.
- var chase_code = code < next_code ? code : prev_code;
- // Chase what we will output, either {CODE} or {CODE-1}.
- var chase_length = 0;
- var chase = chase_code;
- while (chase > clear_code) {
- chase = code_table[chase] >> 8;
- ++chase_length;
- }
- var k = chase;
- var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
- if (op_end > output_length) {
- console.log("Warning, gif stream longer than expected.");
- return;
- }
- // Already have the first byte from the chase, might as well write it fast.
- output[op++] = k;
- op += chase_length;
- var b = op; // Track pointer, writing backwards.
- if (chase_code !== code) // The case of emitting {CODE-1} + k.
- output[op++] = k;
- chase = chase_code;
- while (chase_length--) {
- chase = code_table[chase];
- output[--b] = chase & 0xff; // Write backwards.
- chase >>= 8; // Pull down to the prefix code.
- }
- if (prev_code !== null && next_code < 4096) {
- code_table[next_code++] = prev_code << 8 | k;
- // TODO(deanm): Figure out this clearing vs code growth logic better. I
- // have an feeling that it should just happen somewhere else, for now it
- // is awkward between when we grow past the max and then hit a clear code.
- // For now just check if we hit the max 12-bits (then a clear code should
- // follow, also of course encoded in 12-bits).
- if (next_code >= code_mask+1 && cur_code_size < 12) {
- ++cur_code_size;
- code_mask = code_mask << 1 | 1;
- }
- }
- prev_code = code;
- }
- if (op !== output_length) {
- console.log("Warning, gif stream shorter than expected.");
- }
- return output;
- }
- // CommonJS.
- try { exports.GifWriter = GifWriter; exports.GifReader = GifReader } catch(e) {}
- },{}],265:[function(require,module,exports){
- // Top level file is just a mixin of submodules & constants
- 'use strict';
- var assign = require('./lib/utils/common').assign;
- var deflate = require('./lib/deflate');
- var inflate = require('./lib/inflate');
- var constants = require('./lib/zlib/constants');
- var pako = {};
- assign(pako, deflate, inflate, constants);
- module.exports = pako;
- },{"./lib/deflate":266,"./lib/inflate":267,"./lib/utils/common":268,"./lib/zlib/constants":271}],266:[function(require,module,exports){
- 'use strict';
- var zlib_deflate = require('./zlib/deflate');
- var utils = require('./utils/common');
- var strings = require('./utils/strings');
- var msg = require('./zlib/messages');
- var ZStream = require('./zlib/zstream');
- var toString = Object.prototype.toString;
- /* Public constants ==========================================================*/
- /* ===========================================================================*/
- var Z_NO_FLUSH = 0;
- var Z_FINISH = 4;
- var Z_OK = 0;
- var Z_STREAM_END = 1;
- var Z_SYNC_FLUSH = 2;
- var Z_DEFAULT_COMPRESSION = -1;
- var Z_DEFAULT_STRATEGY = 0;
- var Z_DEFLATED = 8;
- /* ===========================================================================*/
- /**
- * class Deflate
- *
- * Generic JS-style wrapper for zlib calls. If you don't need
- * streaming behaviour - use more simple functions: [[deflate]],
- * [[deflateRaw]] and [[gzip]].
- **/
- /* internal
- * Deflate.chunks -> Array
- *
- * Chunks of output data, if [[Deflate#onData]] not overridden.
- **/
- /**
- * Deflate.result -> Uint8Array|Array
- *
- * Compressed result, generated by default [[Deflate#onData]]
- * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
- * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
- * push a chunk with explicit flush (call [[Deflate#push]] with
- * `Z_SYNC_FLUSH` param).
- **/
- /**
- * Deflate.err -> Number
- *
- * Error code after deflate finished. 0 (Z_OK) on success.
- * You will not need it in real life, because deflate errors
- * are possible only on wrong options or bad `onData` / `onEnd`
- * custom handlers.
- **/
- /**
- * Deflate.msg -> String
- *
- * Error message, if [[Deflate.err]] != 0
- **/
- /**
- * new Deflate(options)
- * - options (Object): zlib deflate options.
- *
- * Creates new deflator instance with specified params. Throws exception
- * on bad params. Supported options:
- *
- * - `level`
- * - `windowBits`
- * - `memLevel`
- * - `strategy`
- * - `dictionary`
- *
- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
- * for more information on these.
- *
- * Additional options, for internal needs:
- *
- * - `chunkSize` - size of generated data chunks (16K by default)
- * - `raw` (Boolean) - do raw deflate
- * - `gzip` (Boolean) - create gzip wrapper
- * - `to` (String) - if equal to 'string', then result will be "binary string"
- * (each char code [0..255])
- * - `header` (Object) - custom header for gzip
- * - `text` (Boolean) - true if compressed data believed to be text
- * - `time` (Number) - modification time, unix timestamp
- * - `os` (Number) - operation system code
- * - `extra` (Array) - array of bytes with extra data (max 65536)
- * - `name` (String) - file name (binary string)
- * - `comment` (String) - comment (binary string)
- * - `hcrc` (Boolean) - true if header crc should be added
- *
- * ##### Example:
- *
- * ```javascript
- * var pako = require('pako')
- * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
- * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
- *
- * var deflate = new pako.Deflate({ level: 3});
- *
- * deflate.push(chunk1, false);
- * deflate.push(chunk2, true); // true -> last chunk
- *
- * if (deflate.err) { throw new Error(deflate.err); }
- *
- * console.log(deflate.result);
- * ```
- **/
- function Deflate(options) {
- if (!(this instanceof Deflate)) return new Deflate(options);
- this.options = utils.assign({
- level: Z_DEFAULT_COMPRESSION,
- method: Z_DEFLATED,
- chunkSize: 16384,
- windowBits: 15,
- memLevel: 8,
- strategy: Z_DEFAULT_STRATEGY,
- to: ''
- }, options || {});
- var opt = this.options;
- if (opt.raw && (opt.windowBits > 0)) {
- opt.windowBits = -opt.windowBits;
- }
- else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
- opt.windowBits += 16;
- }
- this.err = 0; // error code, if happens (0 = Z_OK)
- this.msg = ''; // error message
- this.ended = false; // used to avoid multiple onEnd() calls
- this.chunks = []; // chunks of compressed data
- this.strm = new ZStream();
- this.strm.avail_out = 0;
- var status = zlib_deflate.deflateInit2(
- this.strm,
- opt.level,
- opt.method,
- opt.windowBits,
- opt.memLevel,
- opt.strategy
- );
- if (status !== Z_OK) {
- throw new Error(msg[status]);
- }
- if (opt.header) {
- zlib_deflate.deflateSetHeader(this.strm, opt.header);
- }
- if (opt.dictionary) {
- var dict;
- // Convert data if needed
- if (typeof opt.dictionary === 'string') {
- // If we need to compress text, change encoding to utf8.
- dict = strings.string2buf(opt.dictionary);
- } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
- dict = new Uint8Array(opt.dictionary);
- } else {
- dict = opt.dictionary;
- }
- status = zlib_deflate.deflateSetDictionary(this.strm, dict);
- if (status !== Z_OK) {
- throw new Error(msg[status]);
- }
- this._dict_set = true;
- }
- }
- /**
- * Deflate#push(data[, mode]) -> Boolean
- * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
- * converted to utf8 byte sequence.
- * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
- * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
- *
- * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
- * new compressed chunks. Returns `true` on success. The last data block must have
- * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
- * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
- * can use mode Z_SYNC_FLUSH, keeping the compression context.
- *
- * On fail call [[Deflate#onEnd]] with error code and return false.
- *
- * We strongly recommend to use `Uint8Array` on input for best speed (output
- * array format is detected automatically). Also, don't skip last param and always
- * use the same type in your code (boolean or number). That will improve JS speed.
- *
- * For regular `Array`-s make sure all elements are [0..255].
- *
- * ##### Example
- *
- * ```javascript
- * push(chunk, false); // push one of data chunks
- * ...
- * push(chunk, true); // push last chunk
- * ```
- **/
- Deflate.prototype.push = function (data, mode) {
- var strm = this.strm;
- var chunkSize = this.options.chunkSize;
- var status, _mode;
- if (this.ended) { return false; }
- _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
- // Convert data if needed
- if (typeof data === 'string') {
- // If we need to compress text, change encoding to utf8.
- strm.input = strings.string2buf(data);
- } else if (toString.call(data) === '[object ArrayBuffer]') {
- strm.input = new Uint8Array(data);
- } else {
- strm.input = data;
- }
- strm.next_in = 0;
- strm.avail_in = strm.input.length;
- do {
- if (strm.avail_out === 0) {
- strm.output = new utils.Buf8(chunkSize);
- strm.next_out = 0;
- strm.avail_out = chunkSize;
- }
- status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
- if (status !== Z_STREAM_END && status !== Z_OK) {
- this.onEnd(status);
- this.ended = true;
- return false;
- }
- if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
- if (this.options.to === 'string') {
- this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
- } else {
- this.onData(utils.shrinkBuf(strm.output, strm.next_out));
- }
- }
- } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
- // Finalize on the last chunk.
- if (_mode === Z_FINISH) {
- status = zlib_deflate.deflateEnd(this.strm);
- this.onEnd(status);
- this.ended = true;
- return status === Z_OK;
- }
- // callback interim results if Z_SYNC_FLUSH.
- if (_mode === Z_SYNC_FLUSH) {
- this.onEnd(Z_OK);
- strm.avail_out = 0;
- return true;
- }
- return true;
- };
- /**
- * Deflate#onData(chunk) -> Void
- * - chunk (Uint8Array|Array|String): output data. Type of array depends
- * on js engine support. When string output requested, each chunk
- * will be string.
- *
- * By default, stores data blocks in `chunks[]` property and glue
- * those in `onEnd`. Override this handler, if you need another behaviour.
- **/
- Deflate.prototype.onData = function (chunk) {
- this.chunks.push(chunk);
- };
- /**
- * Deflate#onEnd(status) -> Void
- * - status (Number): deflate status. 0 (Z_OK) on success,
- * other if not.
- *
- * Called once after you tell deflate that the input stream is
- * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
- * or if an error happened. By default - join collected chunks,
- * free memory and fill `results` / `err` properties.
- **/
- Deflate.prototype.onEnd = function (status) {
- // On success - join
- if (status === Z_OK) {
- if (this.options.to === 'string') {
- this.result = this.chunks.join('');
- } else {
- this.result = utils.flattenChunks(this.chunks);
- }
- }
- this.chunks = [];
- this.err = status;
- this.msg = this.strm.msg;
- };
- /**
- * deflate(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to compress.
- * - options (Object): zlib deflate options.
- *
- * Compress `data` with deflate algorithm and `options`.
- *
- * Supported options are:
- *
- * - level
- * - windowBits
- * - memLevel
- * - strategy
- * - dictionary
- *
- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
- * for more information on these.
- *
- * Sugar (options):
- *
- * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
- * negative windowBits implicitly.
- * - `to` (String) - if equal to 'string', then result will be "binary string"
- * (each char code [0..255])
- *
- * ##### Example:
- *
- * ```javascript
- * var pako = require('pako')
- * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
- *
- * console.log(pako.deflate(data));
- * ```
- **/
- function deflate(input, options) {
- var deflator = new Deflate(options);
- deflator.push(input, true);
- // That will never happens, if you don't cheat with options :)
- if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
- return deflator.result;
- }
- /**
- * deflateRaw(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to compress.
- * - options (Object): zlib deflate options.
- *
- * The same as [[deflate]], but creates raw data, without wrapper
- * (header and adler32 crc).
- **/
- function deflateRaw(input, options) {
- options = options || {};
- options.raw = true;
- return deflate(input, options);
- }
- /**
- * gzip(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to compress.
- * - options (Object): zlib deflate options.
- *
- * The same as [[deflate]], but create gzip wrapper instead of
- * deflate one.
- **/
- function gzip(input, options) {
- options = options || {};
- options.gzip = true;
- return deflate(input, options);
- }
- exports.Deflate = Deflate;
- exports.deflate = deflate;
- exports.deflateRaw = deflateRaw;
- exports.gzip = gzip;
- },{"./utils/common":268,"./utils/strings":269,"./zlib/deflate":273,"./zlib/messages":278,"./zlib/zstream":280}],267:[function(require,module,exports){
- 'use strict';
- var zlib_inflate = require('./zlib/inflate');
- var utils = require('./utils/common');
- var strings = require('./utils/strings');
- var c = require('./zlib/constants');
- var msg = require('./zlib/messages');
- var ZStream = require('./zlib/zstream');
- var GZheader = require('./zlib/gzheader');
- var toString = Object.prototype.toString;
- /**
- * class Inflate
- *
- * Generic JS-style wrapper for zlib calls. If you don't need
- * streaming behaviour - use more simple functions: [[inflate]]
- * and [[inflateRaw]].
- **/
- /* internal
- * inflate.chunks -> Array
- *
- * Chunks of output data, if [[Inflate#onData]] not overridden.
- **/
- /**
- * Inflate.result -> Uint8Array|Array|String
- *
- * Uncompressed result, generated by default [[Inflate#onData]]
- * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
- * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
- * push a chunk with explicit flush (call [[Inflate#push]] with
- * `Z_SYNC_FLUSH` param).
- **/
- /**
- * Inflate.err -> Number
- *
- * Error code after inflate finished. 0 (Z_OK) on success.
- * Should be checked if broken data possible.
- **/
- /**
- * Inflate.msg -> String
- *
- * Error message, if [[Inflate.err]] != 0
- **/
- /**
- * new Inflate(options)
- * - options (Object): zlib inflate options.
- *
- * Creates new inflator instance with specified params. Throws exception
- * on bad params. Supported options:
- *
- * - `windowBits`
- * - `dictionary`
- *
- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
- * for more information on these.
- *
- * Additional options, for internal needs:
- *
- * - `chunkSize` - size of generated data chunks (16K by default)
- * - `raw` (Boolean) - do raw inflate
- * - `to` (String) - if equal to 'string', then result will be converted
- * from utf8 to utf16 (javascript) string. When string output requested,
- * chunk length can differ from `chunkSize`, depending on content.
- *
- * By default, when no options set, autodetect deflate/gzip data format via
- * wrapper header.
- *
- * ##### Example:
- *
- * ```javascript
- * var pako = require('pako')
- * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
- * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
- *
- * var inflate = new pako.Inflate({ level: 3});
- *
- * inflate.push(chunk1, false);
- * inflate.push(chunk2, true); // true -> last chunk
- *
- * if (inflate.err) { throw new Error(inflate.err); }
- *
- * console.log(inflate.result);
- * ```
- **/
- function Inflate(options) {
- if (!(this instanceof Inflate)) return new Inflate(options);
- this.options = utils.assign({
- chunkSize: 16384,
- windowBits: 0,
- to: ''
- }, options || {});
- var opt = this.options;
- // Force window size for `raw` data, if not set directly,
- // because we have no header for autodetect.
- if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
- opt.windowBits = -opt.windowBits;
- if (opt.windowBits === 0) { opt.windowBits = -15; }
- }
- // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
- if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
- !(options && options.windowBits)) {
- opt.windowBits += 32;
- }
- // Gzip header has no info about windows size, we can do autodetect only
- // for deflate. So, if window size not set, force it to max when gzip possible
- if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
- // bit 3 (16) -> gzipped data
- // bit 4 (32) -> autodetect gzip/deflate
- if ((opt.windowBits & 15) === 0) {
- opt.windowBits |= 15;
- }
- }
- this.err = 0; // error code, if happens (0 = Z_OK)
- this.msg = ''; // error message
- this.ended = false; // used to avoid multiple onEnd() calls
- this.chunks = []; // chunks of compressed data
- this.strm = new ZStream();
- this.strm.avail_out = 0;
- var status = zlib_inflate.inflateInit2(
- this.strm,
- opt.windowBits
- );
- if (status !== c.Z_OK) {
- throw new Error(msg[status]);
- }
- this.header = new GZheader();
- zlib_inflate.inflateGetHeader(this.strm, this.header);
- }
- /**
- * Inflate#push(data[, mode]) -> Boolean
- * - data (Uint8Array|Array|ArrayBuffer|String): input data
- * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
- * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
- *
- * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
- * new output chunks. Returns `true` on success. The last data block must have
- * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
- * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
- * can use mode Z_SYNC_FLUSH, keeping the decompression context.
- *
- * On fail call [[Inflate#onEnd]] with error code and return false.
- *
- * We strongly recommend to use `Uint8Array` on input for best speed (output
- * format is detected automatically). Also, don't skip last param and always
- * use the same type in your code (boolean or number). That will improve JS speed.
- *
- * For regular `Array`-s make sure all elements are [0..255].
- *
- * ##### Example
- *
- * ```javascript
- * push(chunk, false); // push one of data chunks
- * ...
- * push(chunk, true); // push last chunk
- * ```
- **/
- Inflate.prototype.push = function (data, mode) {
- var strm = this.strm;
- var chunkSize = this.options.chunkSize;
- var dictionary = this.options.dictionary;
- var status, _mode;
- var next_out_utf8, tail, utf8str;
- var dict;
- // Flag to properly process Z_BUF_ERROR on testing inflate call
- // when we check that all output data was flushed.
- var allowBufError = false;
- if (this.ended) { return false; }
- _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
- // Convert data if needed
- if (typeof data === 'string') {
- // Only binary strings can be decompressed on practice
- strm.input = strings.binstring2buf(data);
- } else if (toString.call(data) === '[object ArrayBuffer]') {
- strm.input = new Uint8Array(data);
- } else {
- strm.input = data;
- }
- strm.next_in = 0;
- strm.avail_in = strm.input.length;
- do {
- if (strm.avail_out === 0) {
- strm.output = new utils.Buf8(chunkSize);
- strm.next_out = 0;
- strm.avail_out = chunkSize;
- }
- status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
- if (status === c.Z_NEED_DICT && dictionary) {
- // Convert data if needed
- if (typeof dictionary === 'string') {
- dict = strings.string2buf(dictionary);
- } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
- dict = new Uint8Array(dictionary);
- } else {
- dict = dictionary;
- }
- status = zlib_inflate.inflateSetDictionary(this.strm, dict);
- }
- if (status === c.Z_BUF_ERROR && allowBufError === true) {
- status = c.Z_OK;
- allowBufError = false;
- }
- if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
- this.onEnd(status);
- this.ended = true;
- return false;
- }
- if (strm.next_out) {
- if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
- if (this.options.to === 'string') {
- next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
- tail = strm.next_out - next_out_utf8;
- utf8str = strings.buf2string(strm.output, next_out_utf8);
- // move tail
- strm.next_out = tail;
- strm.avail_out = chunkSize - tail;
- if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
- this.onData(utf8str);
- } else {
- this.onData(utils.shrinkBuf(strm.output, strm.next_out));
- }
- }
- }
- // When no more input data, we should check that internal inflate buffers
- // are flushed. The only way to do it when avail_out = 0 - run one more
- // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
- // Here we set flag to process this error properly.
- //
- // NOTE. Deflate does not return error in this case and does not needs such
- // logic.
- if (strm.avail_in === 0 && strm.avail_out === 0) {
- allowBufError = true;
- }
- } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
- if (status === c.Z_STREAM_END) {
- _mode = c.Z_FINISH;
- }
- // Finalize on the last chunk.
- if (_mode === c.Z_FINISH) {
- status = zlib_inflate.inflateEnd(this.strm);
- this.onEnd(status);
- this.ended = true;
- return status === c.Z_OK;
- }
- // callback interim results if Z_SYNC_FLUSH.
- if (_mode === c.Z_SYNC_FLUSH) {
- this.onEnd(c.Z_OK);
- strm.avail_out = 0;
- return true;
- }
- return true;
- };
- /**
- * Inflate#onData(chunk) -> Void
- * - chunk (Uint8Array|Array|String): output data. Type of array depends
- * on js engine support. When string output requested, each chunk
- * will be string.
- *
- * By default, stores data blocks in `chunks[]` property and glue
- * those in `onEnd`. Override this handler, if you need another behaviour.
- **/
- Inflate.prototype.onData = function (chunk) {
- this.chunks.push(chunk);
- };
- /**
- * Inflate#onEnd(status) -> Void
- * - status (Number): inflate status. 0 (Z_OK) on success,
- * other if not.
- *
- * Called either after you tell inflate that the input stream is
- * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
- * or if an error happened. By default - join collected chunks,
- * free memory and fill `results` / `err` properties.
- **/
- Inflate.prototype.onEnd = function (status) {
- // On success - join
- if (status === c.Z_OK) {
- if (this.options.to === 'string') {
- // Glue & convert here, until we teach pako to send
- // utf8 aligned strings to onData
- this.result = this.chunks.join('');
- } else {
- this.result = utils.flattenChunks(this.chunks);
- }
- }
- this.chunks = [];
- this.err = status;
- this.msg = this.strm.msg;
- };
- /**
- * inflate(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to decompress.
- * - options (Object): zlib inflate options.
- *
- * Decompress `data` with inflate/ungzip and `options`. Autodetect
- * format via wrapper header by default. That's why we don't provide
- * separate `ungzip` method.
- *
- * Supported options are:
- *
- * - windowBits
- *
- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
- * for more information.
- *
- * Sugar (options):
- *
- * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
- * negative windowBits implicitly.
- * - `to` (String) - if equal to 'string', then result will be converted
- * from utf8 to utf16 (javascript) string. When string output requested,
- * chunk length can differ from `chunkSize`, depending on content.
- *
- *
- * ##### Example:
- *
- * ```javascript
- * var pako = require('pako')
- * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
- * , output;
- *
- * try {
- * output = pako.inflate(input);
- * } catch (err)
- * console.log(err);
- * }
- * ```
- **/
- function inflate(input, options) {
- var inflator = new Inflate(options);
- inflator.push(input, true);
- // That will never happens, if you don't cheat with options :)
- if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
- return inflator.result;
- }
- /**
- * inflateRaw(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to decompress.
- * - options (Object): zlib inflate options.
- *
- * The same as [[inflate]], but creates raw data, without wrapper
- * (header and adler32 crc).
- **/
- function inflateRaw(input, options) {
- options = options || {};
- options.raw = true;
- return inflate(input, options);
- }
- /**
- * ungzip(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to decompress.
- * - options (Object): zlib inflate options.
- *
- * Just shortcut to [[inflate]], because it autodetects format
- * by header.content. Done for convenience.
- **/
- exports.Inflate = Inflate;
- exports.inflate = inflate;
- exports.inflateRaw = inflateRaw;
- exports.ungzip = inflate;
- },{"./utils/common":268,"./utils/strings":269,"./zlib/constants":271,"./zlib/gzheader":274,"./zlib/inflate":276,"./zlib/messages":278,"./zlib/zstream":280}],268:[function(require,module,exports){
- arguments[4][35][0].apply(exports,arguments)
- },{"dup":35}],269:[function(require,module,exports){
- // String encode/decode helpers
- 'use strict';
- var utils = require('./common');
- // Quick check if we can use fast array to bin string conversion
- //
- // - apply(Array) can fail on Android 2.2
- // - apply(Uint8Array) can fail on iOS 5.1 Safari
- //
- var STR_APPLY_OK = true;
- var STR_APPLY_UIA_OK = true;
- try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
- try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
- // Table with utf8 lengths (calculated by first byte of sequence)
- // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
- // because max possible codepoint is 0x10ffff
- var _utf8len = new utils.Buf8(256);
- for (var q = 0; q < 256; q++) {
- _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
- }
- _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
- // convert string to array (typed, when possible)
- exports.string2buf = function (str) {
- var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
- // count binary size
- for (m_pos = 0; m_pos < str_len; m_pos++) {
- c = str.charCodeAt(m_pos);
- if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
- c2 = str.charCodeAt(m_pos + 1);
- if ((c2 & 0xfc00) === 0xdc00) {
- c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
- m_pos++;
- }
- }
- buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
- }
- // allocate buffer
- buf = new utils.Buf8(buf_len);
- // convert
- for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
- c = str.charCodeAt(m_pos);
- if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
- c2 = str.charCodeAt(m_pos + 1);
- if ((c2 & 0xfc00) === 0xdc00) {
- c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
- m_pos++;
- }
- }
- if (c < 0x80) {
- /* one byte */
- buf[i++] = c;
- } else if (c < 0x800) {
- /* two bytes */
- buf[i++] = 0xC0 | (c >>> 6);
- buf[i++] = 0x80 | (c & 0x3f);
- } else if (c < 0x10000) {
- /* three bytes */
- buf[i++] = 0xE0 | (c >>> 12);
- buf[i++] = 0x80 | (c >>> 6 & 0x3f);
- buf[i++] = 0x80 | (c & 0x3f);
- } else {
- /* four bytes */
- buf[i++] = 0xf0 | (c >>> 18);
- buf[i++] = 0x80 | (c >>> 12 & 0x3f);
- buf[i++] = 0x80 | (c >>> 6 & 0x3f);
- buf[i++] = 0x80 | (c & 0x3f);
- }
- }
- return buf;
- };
- // Helper (used in 2 places)
- function buf2binstring(buf, len) {
- // use fallback for big arrays to avoid stack overflow
- if (len < 65537) {
- if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
- return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
- }
- }
- var result = '';
- for (var i = 0; i < len; i++) {
- result += String.fromCharCode(buf[i]);
- }
- return result;
- }
- // Convert byte array to binary string
- exports.buf2binstring = function (buf) {
- return buf2binstring(buf, buf.length);
- };
- // Convert binary string (typed, when possible)
- exports.binstring2buf = function (str) {
- var buf = new utils.Buf8(str.length);
- for (var i = 0, len = buf.length; i < len; i++) {
- buf[i] = str.charCodeAt(i);
- }
- return buf;
- };
- // convert array to string
- exports.buf2string = function (buf, max) {
- var i, out, c, c_len;
- var len = max || buf.length;
- // Reserve max possible length (2 words per char)
- // NB: by unknown reasons, Array is significantly faster for
- // String.fromCharCode.apply than Uint16Array.
- var utf16buf = new Array(len * 2);
- for (out = 0, i = 0; i < len;) {
- c = buf[i++];
- // quick process ascii
- if (c < 0x80) { utf16buf[out++] = c; continue; }
- c_len = _utf8len[c];
- // skip 5 & 6 byte codes
- if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
- // apply mask on first byte
- c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
- // join the rest
- while (c_len > 1 && i < len) {
- c = (c << 6) | (buf[i++] & 0x3f);
- c_len--;
- }
- // terminated by end of string?
- if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
- if (c < 0x10000) {
- utf16buf[out++] = c;
- } else {
- c -= 0x10000;
- utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
- utf16buf[out++] = 0xdc00 | (c & 0x3ff);
- }
- }
- return buf2binstring(utf16buf, out);
- };
- // Calculate max possible position in utf8 buffer,
- // that will not break sequence. If that's not possible
- // - (very small limits) return max size as is.
- //
- // buf[] - utf8 bytes array
- // max - length limit (mandatory);
- exports.utf8border = function (buf, max) {
- var pos;
- max = max || buf.length;
- if (max > buf.length) { max = buf.length; }
- // go back from last position, until start of sequence found
- pos = max - 1;
- while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
- // Very small and broken sequence,
- // return max, because we should return something anyway.
- if (pos < 0) { return max; }
- // If we came to start of buffer - that means buffer is too small,
- // return max too.
- if (pos === 0) { return max; }
- return (pos + _utf8len[buf[pos]] > max) ? pos : max;
- };
- },{"./common":268}],270:[function(require,module,exports){
- arguments[4][36][0].apply(exports,arguments)
- },{"dup":36}],271:[function(require,module,exports){
- arguments[4][37][0].apply(exports,arguments)
- },{"dup":37}],272:[function(require,module,exports){
- arguments[4][38][0].apply(exports,arguments)
- },{"dup":38}],273:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- var utils = require('../utils/common');
- var trees = require('./trees');
- var adler32 = require('./adler32');
- var crc32 = require('./crc32');
- var msg = require('./messages');
- /* Public constants ==========================================================*/
- /* ===========================================================================*/
- /* Allowed flush values; see deflate() and inflate() below for details */
- var Z_NO_FLUSH = 0;
- var Z_PARTIAL_FLUSH = 1;
- //var Z_SYNC_FLUSH = 2;
- var Z_FULL_FLUSH = 3;
- var Z_FINISH = 4;
- var Z_BLOCK = 5;
- //var Z_TREES = 6;
- /* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
- var Z_OK = 0;
- var Z_STREAM_END = 1;
- //var Z_NEED_DICT = 2;
- //var Z_ERRNO = -1;
- var Z_STREAM_ERROR = -2;
- var Z_DATA_ERROR = -3;
- //var Z_MEM_ERROR = -4;
- var Z_BUF_ERROR = -5;
- //var Z_VERSION_ERROR = -6;
- /* compression levels */
- //var Z_NO_COMPRESSION = 0;
- //var Z_BEST_SPEED = 1;
- //var Z_BEST_COMPRESSION = 9;
- var Z_DEFAULT_COMPRESSION = -1;
- var Z_FILTERED = 1;
- var Z_HUFFMAN_ONLY = 2;
- var Z_RLE = 3;
- var Z_FIXED = 4;
- var Z_DEFAULT_STRATEGY = 0;
- /* Possible values of the data_type field (though see inflate()) */
- //var Z_BINARY = 0;
- //var Z_TEXT = 1;
- //var Z_ASCII = 1; // = Z_TEXT
- var Z_UNKNOWN = 2;
- /* The deflate compression method */
- var Z_DEFLATED = 8;
- /*============================================================================*/
- var MAX_MEM_LEVEL = 9;
- /* Maximum value for memLevel in deflateInit2 */
- var MAX_WBITS = 15;
- /* 32K LZ77 window */
- var DEF_MEM_LEVEL = 8;
- var LENGTH_CODES = 29;
- /* number of length codes, not counting the special END_BLOCK code */
- var LITERALS = 256;
- /* number of literal bytes 0..255 */
- var L_CODES = LITERALS + 1 + LENGTH_CODES;
- /* number of Literal or Length codes, including the END_BLOCK code */
- var D_CODES = 30;
- /* number of distance codes */
- var BL_CODES = 19;
- /* number of codes used to transfer the bit lengths */
- var HEAP_SIZE = 2 * L_CODES + 1;
- /* maximum heap size */
- var MAX_BITS = 15;
- /* All codes must not exceed MAX_BITS bits */
- var MIN_MATCH = 3;
- var MAX_MATCH = 258;
- var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
- var PRESET_DICT = 0x20;
- var INIT_STATE = 42;
- var EXTRA_STATE = 69;
- var NAME_STATE = 73;
- var COMMENT_STATE = 91;
- var HCRC_STATE = 103;
- var BUSY_STATE = 113;
- var FINISH_STATE = 666;
- var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
- var BS_BLOCK_DONE = 2; /* block flush performed */
- var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
- var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
- var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
- function err(strm, errorCode) {
- strm.msg = msg[errorCode];
- return errorCode;
- }
- function rank(f) {
- return ((f) << 1) - ((f) > 4 ? 9 : 0);
- }
- function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
- /* =========================================================================
- * Flush as much pending output as possible. All deflate() output goes
- * through this function so some applications may wish to modify it
- * to avoid allocating a large strm->output buffer and copying into it.
- * (See also read_buf()).
- */
- function flush_pending(strm) {
- var s = strm.state;
- //_tr_flush_bits(s);
- var len = s.pending;
- if (len > strm.avail_out) {
- len = strm.avail_out;
- }
- if (len === 0) { return; }
- utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
- strm.next_out += len;
- s.pending_out += len;
- strm.total_out += len;
- strm.avail_out -= len;
- s.pending -= len;
- if (s.pending === 0) {
- s.pending_out = 0;
- }
- }
- function flush_block_only(s, last) {
- trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
- s.block_start = s.strstart;
- flush_pending(s.strm);
- }
- function put_byte(s, b) {
- s.pending_buf[s.pending++] = b;
- }
- /* =========================================================================
- * Put a short in the pending buffer. The 16-bit value is put in MSB order.
- * IN assertion: the stream state is correct and there is enough room in
- * pending_buf.
- */
- function putShortMSB(s, b) {
- // put_byte(s, (Byte)(b >> 8));
- // put_byte(s, (Byte)(b & 0xff));
- s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
- s.pending_buf[s.pending++] = b & 0xff;
- }
- /* ===========================================================================
- * Read a new buffer from the current input stream, update the adler32
- * and total number of bytes read. All deflate() input goes through
- * this function so some applications may wish to modify it to avoid
- * allocating a large strm->input buffer and copying from it.
- * (See also flush_pending()).
- */
- function read_buf(strm, buf, start, size) {
- var len = strm.avail_in;
- if (len > size) { len = size; }
- if (len === 0) { return 0; }
- strm.avail_in -= len;
- // zmemcpy(buf, strm->next_in, len);
- utils.arraySet(buf, strm.input, strm.next_in, len, start);
- if (strm.state.wrap === 1) {
- strm.adler = adler32(strm.adler, buf, len, start);
- }
- else if (strm.state.wrap === 2) {
- strm.adler = crc32(strm.adler, buf, len, start);
- }
- strm.next_in += len;
- strm.total_in += len;
- return len;
- }
- /* ===========================================================================
- * Set match_start to the longest match starting at the given string and
- * return its length. Matches shorter or equal to prev_length are discarded,
- * in which case the result is equal to prev_length and match_start is
- * garbage.
- * IN assertions: cur_match is the head of the hash chain for the current
- * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
- * OUT assertion: the match length is not greater than s->lookahead.
- */
- function longest_match(s, cur_match) {
- var chain_length = s.max_chain_length; /* max hash chain length */
- var scan = s.strstart; /* current string */
- var match; /* matched string */
- var len; /* length of current match */
- var best_len = s.prev_length; /* best match length so far */
- var nice_match = s.nice_match; /* stop if match long enough */
- var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
- s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
- var _win = s.window; // shortcut
- var wmask = s.w_mask;
- var prev = s.prev;
- /* Stop when cur_match becomes <= limit. To simplify the code,
- * we prevent matches with the string of window index 0.
- */
- var strend = s.strstart + MAX_MATCH;
- var scan_end1 = _win[scan + best_len - 1];
- var scan_end = _win[scan + best_len];
- /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
- * It is easy to get rid of this optimization if necessary.
- */
- // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
- /* Do not waste too much time if we already have a good match: */
- if (s.prev_length >= s.good_match) {
- chain_length >>= 2;
- }
- /* Do not look for matches beyond the end of the input. This is necessary
- * to make deflate deterministic.
- */
- if (nice_match > s.lookahead) { nice_match = s.lookahead; }
- // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
- do {
- // Assert(cur_match < s->strstart, "no future");
- match = cur_match;
- /* Skip to next match if the match length cannot increase
- * or if the match length is less than 2. Note that the checks below
- * for insufficient lookahead only occur occasionally for performance
- * reasons. Therefore uninitialized memory will be accessed, and
- * conditional jumps will be made that depend on those values.
- * However the length of the match is limited to the lookahead, so
- * the output of deflate is not affected by the uninitialized values.
- */
- if (_win[match + best_len] !== scan_end ||
- _win[match + best_len - 1] !== scan_end1 ||
- _win[match] !== _win[scan] ||
- _win[++match] !== _win[scan + 1]) {
- continue;
- }
- /* The check at best_len-1 can be removed because it will be made
- * again later. (This heuristic is not always a win.)
- * It is not necessary to compare scan[2] and match[2] since they
- * are always equal when the other bytes match, given that
- * the hash keys are equal and that HASH_BITS >= 8.
- */
- scan += 2;
- match++;
- // Assert(*scan == *match, "match[2]?");
- /* We check for insufficient lookahead only every 8th comparison;
- * the 256th check will be made at strstart+258.
- */
- do {
- /*jshint noempty:false*/
- } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- scan < strend);
- // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
- len = MAX_MATCH - (strend - scan);
- scan = strend - MAX_MATCH;
- if (len > best_len) {
- s.match_start = cur_match;
- best_len = len;
- if (len >= nice_match) {
- break;
- }
- scan_end1 = _win[scan + best_len - 1];
- scan_end = _win[scan + best_len];
- }
- } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
- if (best_len <= s.lookahead) {
- return best_len;
- }
- return s.lookahead;
- }
- /* ===========================================================================
- * Fill the window when the lookahead becomes insufficient.
- * Updates strstart and lookahead.
- *
- * IN assertion: lookahead < MIN_LOOKAHEAD
- * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
- * At least one byte has been read, or avail_in == 0; reads are
- * performed for at least two bytes (required for the zip translate_eol
- * option -- not supported here).
- */
- function fill_window(s) {
- var _w_size = s.w_size;
- var p, n, m, more, str;
- //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
- do {
- more = s.window_size - s.lookahead - s.strstart;
- // JS ints have 32 bit, block below not needed
- /* Deal with !@#$% 64K limit: */
- //if (sizeof(int) <= 2) {
- // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
- // more = wsize;
- //
- // } else if (more == (unsigned)(-1)) {
- // /* Very unlikely, but possible on 16 bit machine if
- // * strstart == 0 && lookahead == 1 (input done a byte at time)
- // */
- // more--;
- // }
- //}
- /* If the window is almost full and there is insufficient lookahead,
- * move the upper half to the lower one to make room in the upper half.
- */
- if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
- utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
- s.match_start -= _w_size;
- s.strstart -= _w_size;
- /* we now have strstart >= MAX_DIST */
- s.block_start -= _w_size;
- /* Slide the hash table (could be avoided with 32 bit values
- at the expense of memory usage). We slide even when level == 0
- to keep the hash table consistent if we switch back to level > 0
- later. (Using level 0 permanently is not an optimal usage of
- zlib, so we don't care about this pathological case.)
- */
- n = s.hash_size;
- p = n;
- do {
- m = s.head[--p];
- s.head[p] = (m >= _w_size ? m - _w_size : 0);
- } while (--n);
- n = _w_size;
- p = n;
- do {
- m = s.prev[--p];
- s.prev[p] = (m >= _w_size ? m - _w_size : 0);
- /* If n is not on any hash chain, prev[n] is garbage but
- * its value will never be used.
- */
- } while (--n);
- more += _w_size;
- }
- if (s.strm.avail_in === 0) {
- break;
- }
- /* If there was no sliding:
- * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
- * more == window_size - lookahead - strstart
- * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
- * => more >= window_size - 2*WSIZE + 2
- * In the BIG_MEM or MMAP case (not yet supported),
- * window_size == input_size + MIN_LOOKAHEAD &&
- * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
- * Otherwise, window_size == 2*WSIZE so more >= 2.
- * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
- */
- //Assert(more >= 2, "more < 2");
- n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
- s.lookahead += n;
- /* Initialize the hash value now that we have some input: */
- if (s.lookahead + s.insert >= MIN_MATCH) {
- str = s.strstart - s.insert;
- s.ins_h = s.window[str];
- /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
- //#if MIN_MATCH != 3
- // Call update_hash() MIN_MATCH-3 more times
- //#endif
- while (s.insert) {
- /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
- s.prev[str & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = str;
- str++;
- s.insert--;
- if (s.lookahead + s.insert < MIN_MATCH) {
- break;
- }
- }
- }
- /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
- * but this is not important since only literal bytes will be emitted.
- */
- } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
- /* If the WIN_INIT bytes after the end of the current data have never been
- * written, then zero those bytes in order to avoid memory check reports of
- * the use of uninitialized (or uninitialised as Julian writes) bytes by
- * the longest match routines. Update the high water mark for the next
- * time through here. WIN_INIT is set to MAX_MATCH since the longest match
- * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
- */
- // if (s.high_water < s.window_size) {
- // var curr = s.strstart + s.lookahead;
- // var init = 0;
- //
- // if (s.high_water < curr) {
- // /* Previous high water mark below current data -- zero WIN_INIT
- // * bytes or up to end of window, whichever is less.
- // */
- // init = s.window_size - curr;
- // if (init > WIN_INIT)
- // init = WIN_INIT;
- // zmemzero(s->window + curr, (unsigned)init);
- // s->high_water = curr + init;
- // }
- // else if (s->high_water < (ulg)curr + WIN_INIT) {
- // /* High water mark at or above current data, but below current data
- // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
- // * to end of window, whichever is less.
- // */
- // init = (ulg)curr + WIN_INIT - s->high_water;
- // if (init > s->window_size - s->high_water)
- // init = s->window_size - s->high_water;
- // zmemzero(s->window + s->high_water, (unsigned)init);
- // s->high_water += init;
- // }
- // }
- //
- // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
- // "not enough room for search");
- }
- /* ===========================================================================
- * Copy without compression as much as possible from the input stream, return
- * the current block state.
- * This function does not insert new strings in the dictionary since
- * uncompressible data is probably not useful. This function is used
- * only for the level=0 compression option.
- * NOTE: this function should be optimized to avoid extra copying from
- * window to pending_buf.
- */
- function deflate_stored(s, flush) {
- /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
- * to pending_buf_size, and each stored block has a 5 byte header:
- */
- var max_block_size = 0xffff;
- if (max_block_size > s.pending_buf_size - 5) {
- max_block_size = s.pending_buf_size - 5;
- }
- /* Copy as much as possible from input to output: */
- for (;;) {
- /* Fill the window as much as possible: */
- if (s.lookahead <= 1) {
- //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
- // s->block_start >= (long)s->w_size, "slide too late");
- // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
- // s.block_start >= s.w_size)) {
- // throw new Error("slide too late");
- // }
- fill_window(s);
- if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) {
- break;
- }
- /* flush the current block */
- }
- //Assert(s->block_start >= 0L, "block gone");
- // if (s.block_start < 0) throw new Error("block gone");
- s.strstart += s.lookahead;
- s.lookahead = 0;
- /* Emit a stored block if pending_buf will be full: */
- var max_start = s.block_start + max_block_size;
- if (s.strstart === 0 || s.strstart >= max_start) {
- /* strstart == 0 is possible when wraparound on 16-bit machine */
- s.lookahead = s.strstart - max_start;
- s.strstart = max_start;
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- /* Flush if we may have to slide, otherwise block_start may become
- * negative and the data will be gone:
- */
- if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.strstart > s.block_start) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_NEED_MORE;
- }
- /* ===========================================================================
- * Compress as much as possible from the input stream, return the current
- * block state.
- * This function does not perform lazy evaluation of matches and inserts
- * new strings in the dictionary only for unmatched strings or for short
- * matches. It is used only for the fast compression options.
- */
- function deflate_fast(s, flush) {
- var hash_head; /* head of the hash chain */
- var bflush; /* set if current block must be flushed */
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the next match, plus MIN_MATCH bytes to insert the
- * string following the next match.
- */
- if (s.lookahead < MIN_LOOKAHEAD) {
- fill_window(s);
- if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) {
- break; /* flush the current block */
- }
- }
- /* Insert the string window[strstart .. strstart+2] in the
- * dictionary, and set hash_head to the head of the hash chain:
- */
- hash_head = 0/*NIL*/;
- if (s.lookahead >= MIN_MATCH) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
- /* Find the longest match, discarding those <= prev_length.
- * At this point we have always match_length < MIN_MATCH
- */
- if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
- /* To simplify the code, we prevent matches with the string
- * of window index 0 (in particular we have to avoid a match
- * of the string with itself at the start of the input file).
- */
- s.match_length = longest_match(s, hash_head);
- /* longest_match() sets match_start */
- }
- if (s.match_length >= MIN_MATCH) {
- // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
- /*** _tr_tally_dist(s, s.strstart - s.match_start,
- s.match_length - MIN_MATCH, bflush); ***/
- bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
- s.lookahead -= s.match_length;
- /* Insert new strings in the hash table only if the match length
- * is not too large. This saves time but degrades compression.
- */
- if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
- s.match_length--; /* string at strstart already in table */
- do {
- s.strstart++;
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- /* strstart never exceeds WSIZE-MAX_MATCH, so there are
- * always MIN_MATCH bytes ahead.
- */
- } while (--s.match_length !== 0);
- s.strstart++;
- } else
- {
- s.strstart += s.match_length;
- s.match_length = 0;
- s.ins_h = s.window[s.strstart];
- /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
- //#if MIN_MATCH != 3
- // Call UPDATE_HASH() MIN_MATCH-3 more times
- //#endif
- /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
- * matter since it will be recomputed at next deflate call.
- */
- }
- } else {
- /* No match, output a literal byte */
- //Tracevv((stderr,"%c", s.window[s.strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
- s.lookahead--;
- s.strstart++;
- }
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* ===========================================================================
- * Same as above, but achieves better compression. We use a lazy
- * evaluation for matches: a match is finally adopted only if there is
- * no better match at the next window position.
- */
- function deflate_slow(s, flush) {
- var hash_head; /* head of hash chain */
- var bflush; /* set if current block must be flushed */
- var max_insert;
- /* Process the input block. */
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the next match, plus MIN_MATCH bytes to insert the
- * string following the next match.
- */
- if (s.lookahead < MIN_LOOKAHEAD) {
- fill_window(s);
- if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) { break; } /* flush the current block */
- }
- /* Insert the string window[strstart .. strstart+2] in the
- * dictionary, and set hash_head to the head of the hash chain:
- */
- hash_head = 0/*NIL*/;
- if (s.lookahead >= MIN_MATCH) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
- /* Find the longest match, discarding those <= prev_length.
- */
- s.prev_length = s.match_length;
- s.prev_match = s.match_start;
- s.match_length = MIN_MATCH - 1;
- if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
- s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
- /* To simplify the code, we prevent matches with the string
- * of window index 0 (in particular we have to avoid a match
- * of the string with itself at the start of the input file).
- */
- s.match_length = longest_match(s, hash_head);
- /* longest_match() sets match_start */
- if (s.match_length <= 5 &&
- (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
- /* If prev_match is also MIN_MATCH, match_start is garbage
- * but we will ignore the current match anyway.
- */
- s.match_length = MIN_MATCH - 1;
- }
- }
- /* If there was a match at the previous step and the current
- * match is not better, output the previous match:
- */
- if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
- max_insert = s.strstart + s.lookahead - MIN_MATCH;
- /* Do not insert strings in hash table beyond this. */
- //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
- /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
- s.prev_length - MIN_MATCH, bflush);***/
- bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
- /* Insert in hash table all strings up to the end of the match.
- * strstart-1 and strstart are already inserted. If there is not
- * enough lookahead, the last two strings are not inserted in
- * the hash table.
- */
- s.lookahead -= s.prev_length - 1;
- s.prev_length -= 2;
- do {
- if (++s.strstart <= max_insert) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
- } while (--s.prev_length !== 0);
- s.match_available = 0;
- s.match_length = MIN_MATCH - 1;
- s.strstart++;
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- } else if (s.match_available) {
- /* If there was no match at the previous position, output a
- * single literal. If there was a match but the current match
- * is longer, truncate the previous match to a single literal.
- */
- //Tracevv((stderr,"%c", s->window[s->strstart-1]));
- /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
- if (bflush) {
- /*** FLUSH_BLOCK_ONLY(s, 0) ***/
- flush_block_only(s, false);
- /***/
- }
- s.strstart++;
- s.lookahead--;
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- } else {
- /* There is no previous match to compare with, wait for
- * the next step to decide.
- */
- s.match_available = 1;
- s.strstart++;
- s.lookahead--;
- }
- }
- //Assert (flush != Z_NO_FLUSH, "no flush?");
- if (s.match_available) {
- //Tracevv((stderr,"%c", s->window[s->strstart-1]));
- /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
- s.match_available = 0;
- }
- s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* ===========================================================================
- * For Z_RLE, simply look for runs of bytes, generate matches only of distance
- * one. Do not maintain a hash table. (It will be regenerated if this run of
- * deflate switches away from Z_RLE.)
- */
- function deflate_rle(s, flush) {
- var bflush; /* set if current block must be flushed */
- var prev; /* byte at distance one to match */
- var scan, strend; /* scan goes up to strend for length of run */
- var _win = s.window;
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the longest run, plus one for the unrolled loop.
- */
- if (s.lookahead <= MAX_MATCH) {
- fill_window(s);
- if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) { break; } /* flush the current block */
- }
- /* See how many times the previous byte repeats */
- s.match_length = 0;
- if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
- scan = s.strstart - 1;
- prev = _win[scan];
- if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
- strend = s.strstart + MAX_MATCH;
- do {
- /*jshint noempty:false*/
- } while (prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- scan < strend);
- s.match_length = MAX_MATCH - (strend - scan);
- if (s.match_length > s.lookahead) {
- s.match_length = s.lookahead;
- }
- }
- //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
- }
- /* Emit match if have run of MIN_MATCH or longer, else emit literal */
- if (s.match_length >= MIN_MATCH) {
- //check_match(s, s.strstart, s.strstart - 1, s.match_length);
- /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
- bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
- s.lookahead -= s.match_length;
- s.strstart += s.match_length;
- s.match_length = 0;
- } else {
- /* No match, output a literal byte */
- //Tracevv((stderr,"%c", s->window[s->strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
- s.lookahead--;
- s.strstart++;
- }
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* ===========================================================================
- * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
- * (It will be regenerated if this run of deflate switches away from Huffman.)
- */
- function deflate_huff(s, flush) {
- var bflush; /* set if current block must be flushed */
- for (;;) {
- /* Make sure that we have a literal to write. */
- if (s.lookahead === 0) {
- fill_window(s);
- if (s.lookahead === 0) {
- if (flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- break; /* flush the current block */
- }
- }
- /* Output a literal byte */
- s.match_length = 0;
- //Tracevv((stderr,"%c", s->window[s->strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
- s.lookahead--;
- s.strstart++;
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* Values for max_lazy_match, good_match and max_chain_length, depending on
- * the desired pack level (0..9). The values given below have been tuned to
- * exclude worst case performance for pathological files. Better values may be
- * found for specific files.
- */
- function Config(good_length, max_lazy, nice_length, max_chain, func) {
- this.good_length = good_length;
- this.max_lazy = max_lazy;
- this.nice_length = nice_length;
- this.max_chain = max_chain;
- this.func = func;
- }
- var configuration_table;
- configuration_table = [
- /* good lazy nice chain */
- new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
- new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
- new Config(4, 5, 16, 8, deflate_fast), /* 2 */
- new Config(4, 6, 32, 32, deflate_fast), /* 3 */
- new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
- new Config(8, 16, 32, 32, deflate_slow), /* 5 */
- new Config(8, 16, 128, 128, deflate_slow), /* 6 */
- new Config(8, 32, 128, 256, deflate_slow), /* 7 */
- new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
- new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
- ];
- /* ===========================================================================
- * Initialize the "longest match" routines for a new zlib stream
- */
- function lm_init(s) {
- s.window_size = 2 * s.w_size;
- /*** CLEAR_HASH(s); ***/
- zero(s.head); // Fill with NIL (= 0);
- /* Set the default configuration parameters:
- */
- s.max_lazy_match = configuration_table[s.level].max_lazy;
- s.good_match = configuration_table[s.level].good_length;
- s.nice_match = configuration_table[s.level].nice_length;
- s.max_chain_length = configuration_table[s.level].max_chain;
- s.strstart = 0;
- s.block_start = 0;
- s.lookahead = 0;
- s.insert = 0;
- s.match_length = s.prev_length = MIN_MATCH - 1;
- s.match_available = 0;
- s.ins_h = 0;
- }
- function DeflateState() {
- this.strm = null; /* pointer back to this zlib stream */
- this.status = 0; /* as the name implies */
- this.pending_buf = null; /* output still pending */
- this.pending_buf_size = 0; /* size of pending_buf */
- this.pending_out = 0; /* next pending byte to output to the stream */
- this.pending = 0; /* nb of bytes in the pending buffer */
- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
- this.gzhead = null; /* gzip header information to write */
- this.gzindex = 0; /* where in extra, name, or comment */
- this.method = Z_DEFLATED; /* can only be DEFLATED */
- this.last_flush = -1; /* value of flush param for previous deflate call */
- this.w_size = 0; /* LZ77 window size (32K by default) */
- this.w_bits = 0; /* log2(w_size) (8..16) */
- this.w_mask = 0; /* w_size - 1 */
- this.window = null;
- /* Sliding window. Input bytes are read into the second half of the window,
- * and move to the first half later to keep a dictionary of at least wSize
- * bytes. With this organization, matches are limited to a distance of
- * wSize-MAX_MATCH bytes, but this ensures that IO is always
- * performed with a length multiple of the block size.
- */
- this.window_size = 0;
- /* Actual size of window: 2*wSize, except when the user input buffer
- * is directly used as sliding window.
- */
- this.prev = null;
- /* Link to older string with same hash index. To limit the size of this
- * array to 64K, this link is maintained only for the last 32K strings.
- * An index in this array is thus a window index modulo 32K.
- */
- this.head = null; /* Heads of the hash chains or NIL. */
- this.ins_h = 0; /* hash index of string to be inserted */
- this.hash_size = 0; /* number of elements in hash table */
- this.hash_bits = 0; /* log2(hash_size) */
- this.hash_mask = 0; /* hash_size-1 */
- this.hash_shift = 0;
- /* Number of bits by which ins_h must be shifted at each input
- * step. It must be such that after MIN_MATCH steps, the oldest
- * byte no longer takes part in the hash key, that is:
- * hash_shift * MIN_MATCH >= hash_bits
- */
- this.block_start = 0;
- /* Window position at the beginning of the current output block. Gets
- * negative when the window is moved backwards.
- */
- this.match_length = 0; /* length of best match */
- this.prev_match = 0; /* previous match */
- this.match_available = 0; /* set if previous match exists */
- this.strstart = 0; /* start of string to insert */
- this.match_start = 0; /* start of matching string */
- this.lookahead = 0; /* number of valid bytes ahead in window */
- this.prev_length = 0;
- /* Length of the best match at previous step. Matches not greater than this
- * are discarded. This is used in the lazy match evaluation.
- */
- this.max_chain_length = 0;
- /* To speed up deflation, hash chains are never searched beyond this
- * length. A higher limit improves compression ratio but degrades the
- * speed.
- */
- this.max_lazy_match = 0;
- /* Attempt to find a better match only when the current match is strictly
- * smaller than this value. This mechanism is used only for compression
- * levels >= 4.
- */
- // That's alias to max_lazy_match, don't use directly
- //this.max_insert_length = 0;
- /* Insert new strings in the hash table only if the match length is not
- * greater than this length. This saves time but degrades compression.
- * max_insert_length is used only for compression levels <= 3.
- */
- this.level = 0; /* compression level (1..9) */
- this.strategy = 0; /* favor or force Huffman coding*/
- this.good_match = 0;
- /* Use a faster search when the previous match is longer than this */
- this.nice_match = 0; /* Stop searching when current match exceeds this */
- /* used by trees.c: */
- /* Didn't use ct_data typedef below to suppress compiler warning */
- // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
- // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
- // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
- // Use flat array of DOUBLE size, with interleaved fata,
- // because JS does not support effective
- this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
- this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
- this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
- zero(this.dyn_ltree);
- zero(this.dyn_dtree);
- zero(this.bl_tree);
- this.l_desc = null; /* desc. for literal tree */
- this.d_desc = null; /* desc. for distance tree */
- this.bl_desc = null; /* desc. for bit length tree */
- //ush bl_count[MAX_BITS+1];
- this.bl_count = new utils.Buf16(MAX_BITS + 1);
- /* number of codes at each bit length for an optimal tree */
- //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
- this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
- zero(this.heap);
- this.heap_len = 0; /* number of elements in the heap */
- this.heap_max = 0; /* element of largest frequency */
- /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
- * The same heap array is used to build all trees.
- */
- this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
- zero(this.depth);
- /* Depth of each subtree used as tie breaker for trees of equal frequency
- */
- this.l_buf = 0; /* buffer index for literals or lengths */
- this.lit_bufsize = 0;
- /* Size of match buffer for literals/lengths. There are 4 reasons for
- * limiting lit_bufsize to 64K:
- * - frequencies can be kept in 16 bit counters
- * - if compression is not successful for the first block, all input
- * data is still in the window so we can still emit a stored block even
- * when input comes from standard input. (This can also be done for
- * all blocks if lit_bufsize is not greater than 32K.)
- * - if compression is not successful for a file smaller than 64K, we can
- * even emit a stored file instead of a stored block (saving 5 bytes).
- * This is applicable only for zip (not gzip or zlib).
- * - creating new Huffman trees less frequently may not provide fast
- * adaptation to changes in the input data statistics. (Take for
- * example a binary file with poorly compressible code followed by
- * a highly compressible string table.) Smaller buffer sizes give
- * fast adaptation but have of course the overhead of transmitting
- * trees more frequently.
- * - I can't count above 4
- */
- this.last_lit = 0; /* running index in l_buf */
- this.d_buf = 0;
- /* Buffer index for distances. To simplify the code, d_buf and l_buf have
- * the same number of elements. To use different lengths, an extra flag
- * array would be necessary.
- */
- this.opt_len = 0; /* bit length of current block with optimal trees */
- this.static_len = 0; /* bit length of current block with static trees */
- this.matches = 0; /* number of string matches in current block */
- this.insert = 0; /* bytes at end of window left to insert */
- this.bi_buf = 0;
- /* Output buffer. bits are inserted starting at the bottom (least
- * significant bits).
- */
- this.bi_valid = 0;
- /* Number of valid bits in bi_buf. All bits above the last valid bit
- * are always zero.
- */
- // Used for window memory init. We safely ignore it for JS. That makes
- // sense only for pointers and memory check tools.
- //this.high_water = 0;
- /* High water mark offset in window for initialized bytes -- bytes above
- * this are set to zero in order to avoid memory check warnings when
- * longest match routines access bytes past the input. This is then
- * updated to the new high water mark.
- */
- }
- function deflateResetKeep(strm) {
- var s;
- if (!strm || !strm.state) {
- return err(strm, Z_STREAM_ERROR);
- }
- strm.total_in = strm.total_out = 0;
- strm.data_type = Z_UNKNOWN;
- s = strm.state;
- s.pending = 0;
- s.pending_out = 0;
- if (s.wrap < 0) {
- s.wrap = -s.wrap;
- /* was made negative by deflate(..., Z_FINISH); */
- }
- s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
- strm.adler = (s.wrap === 2) ?
- 0 // crc32(0, Z_NULL, 0)
- :
- 1; // adler32(0, Z_NULL, 0)
- s.last_flush = Z_NO_FLUSH;
- trees._tr_init(s);
- return Z_OK;
- }
- function deflateReset(strm) {
- var ret = deflateResetKeep(strm);
- if (ret === Z_OK) {
- lm_init(strm.state);
- }
- return ret;
- }
- function deflateSetHeader(strm, head) {
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
- strm.state.gzhead = head;
- return Z_OK;
- }
- function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
- if (!strm) { // === Z_NULL
- return Z_STREAM_ERROR;
- }
- var wrap = 1;
- if (level === Z_DEFAULT_COMPRESSION) {
- level = 6;
- }
- if (windowBits < 0) { /* suppress zlib wrapper */
- wrap = 0;
- windowBits = -windowBits;
- }
- else if (windowBits > 15) {
- wrap = 2; /* write gzip wrapper instead */
- windowBits -= 16;
- }
- if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
- windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
- strategy < 0 || strategy > Z_FIXED) {
- return err(strm, Z_STREAM_ERROR);
- }
- if (windowBits === 8) {
- windowBits = 9;
- }
- /* until 256-byte window bug fixed */
- var s = new DeflateState();
- strm.state = s;
- s.strm = strm;
- s.wrap = wrap;
- s.gzhead = null;
- s.w_bits = windowBits;
- s.w_size = 1 << s.w_bits;
- s.w_mask = s.w_size - 1;
- s.hash_bits = memLevel + 7;
- s.hash_size = 1 << s.hash_bits;
- s.hash_mask = s.hash_size - 1;
- s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
- s.window = new utils.Buf8(s.w_size * 2);
- s.head = new utils.Buf16(s.hash_size);
- s.prev = new utils.Buf16(s.w_size);
- // Don't need mem init magic for JS.
- //s.high_water = 0; /* nothing written to s->window yet */
- s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
- s.pending_buf_size = s.lit_bufsize * 4;
- //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
- //s->pending_buf = (uchf *) overlay;
- s.pending_buf = new utils.Buf8(s.pending_buf_size);
- // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
- //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
- s.d_buf = 1 * s.lit_bufsize;
- //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
- s.l_buf = (1 + 2) * s.lit_bufsize;
- s.level = level;
- s.strategy = strategy;
- s.method = method;
- return deflateReset(strm);
- }
- function deflateInit(strm, level) {
- return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
- }
- function deflate(strm, flush) {
- var old_flush, s;
- var beg, val; // for gzip header write only
- if (!strm || !strm.state ||
- flush > Z_BLOCK || flush < 0) {
- return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
- }
- s = strm.state;
- if (!strm.output ||
- (!strm.input && strm.avail_in !== 0) ||
- (s.status === FINISH_STATE && flush !== Z_FINISH)) {
- return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
- }
- s.strm = strm; /* just in case */
- old_flush = s.last_flush;
- s.last_flush = flush;
- /* Write the header */
- if (s.status === INIT_STATE) {
- if (s.wrap === 2) { // GZIP header
- strm.adler = 0; //crc32(0L, Z_NULL, 0);
- put_byte(s, 31);
- put_byte(s, 139);
- put_byte(s, 8);
- if (!s.gzhead) { // s->gzhead == Z_NULL
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, s.level === 9 ? 2 :
- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
- 4 : 0));
- put_byte(s, OS_CODE);
- s.status = BUSY_STATE;
- }
- else {
- put_byte(s, (s.gzhead.text ? 1 : 0) +
- (s.gzhead.hcrc ? 2 : 0) +
- (!s.gzhead.extra ? 0 : 4) +
- (!s.gzhead.name ? 0 : 8) +
- (!s.gzhead.comment ? 0 : 16)
- );
- put_byte(s, s.gzhead.time & 0xff);
- put_byte(s, (s.gzhead.time >> 8) & 0xff);
- put_byte(s, (s.gzhead.time >> 16) & 0xff);
- put_byte(s, (s.gzhead.time >> 24) & 0xff);
- put_byte(s, s.level === 9 ? 2 :
- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
- 4 : 0));
- put_byte(s, s.gzhead.os & 0xff);
- if (s.gzhead.extra && s.gzhead.extra.length) {
- put_byte(s, s.gzhead.extra.length & 0xff);
- put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
- }
- if (s.gzhead.hcrc) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
- }
- s.gzindex = 0;
- s.status = EXTRA_STATE;
- }
- }
- else // DEFLATE header
- {
- var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
- var level_flags = -1;
- if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
- level_flags = 0;
- } else if (s.level < 6) {
- level_flags = 1;
- } else if (s.level === 6) {
- level_flags = 2;
- } else {
- level_flags = 3;
- }
- header |= (level_flags << 6);
- if (s.strstart !== 0) { header |= PRESET_DICT; }
- header += 31 - (header % 31);
- s.status = BUSY_STATE;
- putShortMSB(s, header);
- /* Save the adler32 of the preset dictionary: */
- if (s.strstart !== 0) {
- putShortMSB(s, strm.adler >>> 16);
- putShortMSB(s, strm.adler & 0xffff);
- }
- strm.adler = 1; // adler32(0L, Z_NULL, 0);
- }
- }
- //#ifdef GZIP
- if (s.status === EXTRA_STATE) {
- if (s.gzhead.extra/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- break;
- }
- }
- put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
- s.gzindex++;
- }
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (s.gzindex === s.gzhead.extra.length) {
- s.gzindex = 0;
- s.status = NAME_STATE;
- }
- }
- else {
- s.status = NAME_STATE;
- }
- }
- if (s.status === NAME_STATE) {
- if (s.gzhead.name/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- //int val;
- do {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- val = 1;
- break;
- }
- }
- // JS specific: little magic to add zero terminator to end of string
- if (s.gzindex < s.gzhead.name.length) {
- val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
- } else {
- val = 0;
- }
- put_byte(s, val);
- } while (val !== 0);
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (val === 0) {
- s.gzindex = 0;
- s.status = COMMENT_STATE;
- }
- }
- else {
- s.status = COMMENT_STATE;
- }
- }
- if (s.status === COMMENT_STATE) {
- if (s.gzhead.comment/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- //int val;
- do {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- val = 1;
- break;
- }
- }
- // JS specific: little magic to add zero terminator to end of string
- if (s.gzindex < s.gzhead.comment.length) {
- val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
- } else {
- val = 0;
- }
- put_byte(s, val);
- } while (val !== 0);
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (val === 0) {
- s.status = HCRC_STATE;
- }
- }
- else {
- s.status = HCRC_STATE;
- }
- }
- if (s.status === HCRC_STATE) {
- if (s.gzhead.hcrc) {
- if (s.pending + 2 > s.pending_buf_size) {
- flush_pending(strm);
- }
- if (s.pending + 2 <= s.pending_buf_size) {
- put_byte(s, strm.adler & 0xff);
- put_byte(s, (strm.adler >> 8) & 0xff);
- strm.adler = 0; //crc32(0L, Z_NULL, 0);
- s.status = BUSY_STATE;
- }
- }
- else {
- s.status = BUSY_STATE;
- }
- }
- //#endif
- /* Flush as much pending output as possible */
- if (s.pending !== 0) {
- flush_pending(strm);
- if (strm.avail_out === 0) {
- /* Since avail_out is 0, deflate will be called again with
- * more output space, but possibly with both pending and
- * avail_in equal to zero. There won't be anything to do,
- * but this is not an error situation so make sure we
- * return OK instead of BUF_ERROR at next call of deflate:
- */
- s.last_flush = -1;
- return Z_OK;
- }
- /* Make sure there is something to do and avoid duplicate consecutive
- * flushes. For repeated and useless calls with Z_FINISH, we keep
- * returning Z_STREAM_END instead of Z_BUF_ERROR.
- */
- } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
- flush !== Z_FINISH) {
- return err(strm, Z_BUF_ERROR);
- }
- /* User must not provide more input after the first FINISH: */
- if (s.status === FINISH_STATE && strm.avail_in !== 0) {
- return err(strm, Z_BUF_ERROR);
- }
- /* Start a new block or continue the current one.
- */
- if (strm.avail_in !== 0 || s.lookahead !== 0 ||
- (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
- var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
- (s.strategy === Z_RLE ? deflate_rle(s, flush) :
- configuration_table[s.level].func(s, flush));
- if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
- s.status = FINISH_STATE;
- }
- if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
- if (strm.avail_out === 0) {
- s.last_flush = -1;
- /* avoid BUF_ERROR next call, see above */
- }
- return Z_OK;
- /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
- * of deflate should use the same flush parameter to make sure
- * that the flush is complete. So we don't have to output an
- * empty block here, this will be done at next call. This also
- * ensures that for a very small output buffer, we emit at most
- * one empty block.
- */
- }
- if (bstate === BS_BLOCK_DONE) {
- if (flush === Z_PARTIAL_FLUSH) {
- trees._tr_align(s);
- }
- else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
- trees._tr_stored_block(s, 0, 0, false);
- /* For a full flush, this empty block will be recognized
- * as a special marker by inflate_sync().
- */
- if (flush === Z_FULL_FLUSH) {
- /*** CLEAR_HASH(s); ***/ /* forget history */
- zero(s.head); // Fill with NIL (= 0);
- if (s.lookahead === 0) {
- s.strstart = 0;
- s.block_start = 0;
- s.insert = 0;
- }
- }
- }
- flush_pending(strm);
- if (strm.avail_out === 0) {
- s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
- return Z_OK;
- }
- }
- }
- //Assert(strm->avail_out > 0, "bug2");
- //if (strm.avail_out <= 0) { throw new Error("bug2");}
- if (flush !== Z_FINISH) { return Z_OK; }
- if (s.wrap <= 0) { return Z_STREAM_END; }
- /* Write the trailer */
- if (s.wrap === 2) {
- put_byte(s, strm.adler & 0xff);
- put_byte(s, (strm.adler >> 8) & 0xff);
- put_byte(s, (strm.adler >> 16) & 0xff);
- put_byte(s, (strm.adler >> 24) & 0xff);
- put_byte(s, strm.total_in & 0xff);
- put_byte(s, (strm.total_in >> 8) & 0xff);
- put_byte(s, (strm.total_in >> 16) & 0xff);
- put_byte(s, (strm.total_in >> 24) & 0xff);
- }
- else
- {
- putShortMSB(s, strm.adler >>> 16);
- putShortMSB(s, strm.adler & 0xffff);
- }
- flush_pending(strm);
- /* If avail_out is zero, the application will call deflate again
- * to flush the rest.
- */
- if (s.wrap > 0) { s.wrap = -s.wrap; }
- /* write the trailer only once! */
- return s.pending !== 0 ? Z_OK : Z_STREAM_END;
- }
- function deflateEnd(strm) {
- var status;
- if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
- return Z_STREAM_ERROR;
- }
- status = strm.state.status;
- if (status !== INIT_STATE &&
- status !== EXTRA_STATE &&
- status !== NAME_STATE &&
- status !== COMMENT_STATE &&
- status !== HCRC_STATE &&
- status !== BUSY_STATE &&
- status !== FINISH_STATE
- ) {
- return err(strm, Z_STREAM_ERROR);
- }
- strm.state = null;
- return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
- }
- /* =========================================================================
- * Initializes the compression dictionary from the given byte
- * sequence without producing any compressed output.
- */
- function deflateSetDictionary(strm, dictionary) {
- var dictLength = dictionary.length;
- var s;
- var str, n;
- var wrap;
- var avail;
- var next;
- var input;
- var tmpDict;
- if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
- return Z_STREAM_ERROR;
- }
- s = strm.state;
- wrap = s.wrap;
- if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
- return Z_STREAM_ERROR;
- }
- /* when using zlib wrappers, compute Adler-32 for provided dictionary */
- if (wrap === 1) {
- /* adler32(strm->adler, dictionary, dictLength); */
- strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
- }
- s.wrap = 0; /* avoid computing Adler-32 in read_buf */
- /* if dictionary would fill window, just replace the history */
- if (dictLength >= s.w_size) {
- if (wrap === 0) { /* already empty otherwise */
- /*** CLEAR_HASH(s); ***/
- zero(s.head); // Fill with NIL (= 0);
- s.strstart = 0;
- s.block_start = 0;
- s.insert = 0;
- }
- /* use the tail */
- // dictionary = dictionary.slice(dictLength - s.w_size);
- tmpDict = new utils.Buf8(s.w_size);
- utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
- dictionary = tmpDict;
- dictLength = s.w_size;
- }
- /* insert dictionary into window and hash */
- avail = strm.avail_in;
- next = strm.next_in;
- input = strm.input;
- strm.avail_in = dictLength;
- strm.next_in = 0;
- strm.input = dictionary;
- fill_window(s);
- while (s.lookahead >= MIN_MATCH) {
- str = s.strstart;
- n = s.lookahead - (MIN_MATCH - 1);
- do {
- /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
- s.prev[str & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = str;
- str++;
- } while (--n);
- s.strstart = str;
- s.lookahead = MIN_MATCH - 1;
- fill_window(s);
- }
- s.strstart += s.lookahead;
- s.block_start = s.strstart;
- s.insert = s.lookahead;
- s.lookahead = 0;
- s.match_length = s.prev_length = MIN_MATCH - 1;
- s.match_available = 0;
- strm.next_in = next;
- strm.input = input;
- strm.avail_in = avail;
- s.wrap = wrap;
- return Z_OK;
- }
- exports.deflateInit = deflateInit;
- exports.deflateInit2 = deflateInit2;
- exports.deflateReset = deflateReset;
- exports.deflateResetKeep = deflateResetKeep;
- exports.deflateSetHeader = deflateSetHeader;
- exports.deflate = deflate;
- exports.deflateEnd = deflateEnd;
- exports.deflateSetDictionary = deflateSetDictionary;
- exports.deflateInfo = 'pako deflate (from Nodeca project)';
- /* Not implemented
- exports.deflateBound = deflateBound;
- exports.deflateCopy = deflateCopy;
- exports.deflateParams = deflateParams;
- exports.deflatePending = deflatePending;
- exports.deflatePrime = deflatePrime;
- exports.deflateTune = deflateTune;
- */
- },{"../utils/common":268,"./adler32":270,"./crc32":272,"./messages":278,"./trees":279}],274:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- function GZheader() {
- /* true if compressed data believed to be text */
- this.text = 0;
- /* modification time */
- this.time = 0;
- /* extra flags (not used when writing a gzip file) */
- this.xflags = 0;
- /* operating system */
- this.os = 0;
- /* pointer to extra field or Z_NULL if none */
- this.extra = null;
- /* extra field length (valid if extra != Z_NULL) */
- this.extra_len = 0; // Actually, we don't need it in JS,
- // but leave for few code modifications
- //
- // Setup limits is not necessary because in js we should not preallocate memory
- // for inflate use constant limit in 65536 bytes
- //
- /* space at extra (only when reading header) */
- // this.extra_max = 0;
- /* pointer to zero-terminated file name or Z_NULL */
- this.name = '';
- /* space at name (only when reading header) */
- // this.name_max = 0;
- /* pointer to zero-terminated comment or Z_NULL */
- this.comment = '';
- /* space at comment (only when reading header) */
- // this.comm_max = 0;
- /* true if there was or will be a header crc */
- this.hcrc = 0;
- /* true when done reading gzip header (not used when writing a gzip file) */
- this.done = false;
- }
- module.exports = GZheader;
- },{}],275:[function(require,module,exports){
- arguments[4][40][0].apply(exports,arguments)
- },{"dup":40}],276:[function(require,module,exports){
- arguments[4][41][0].apply(exports,arguments)
- },{"../utils/common":268,"./adler32":270,"./crc32":272,"./inffast":275,"./inftrees":277,"dup":41}],277:[function(require,module,exports){
- arguments[4][42][0].apply(exports,arguments)
- },{"../utils/common":268,"dup":42}],278:[function(require,module,exports){
- arguments[4][43][0].apply(exports,arguments)
- },{"dup":43}],279:[function(require,module,exports){
- 'use strict';
- // (C) 1995-2013 Jean-loup Gailly and Mark Adler
- // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
- //
- // This software is provided 'as-is', without any express or implied
- // warranty. In no event will the authors be held liable for any damages
- // arising from the use of this software.
- //
- // Permission is granted to anyone to use this software for any purpose,
- // including commercial applications, and to alter it and redistribute it
- // freely, subject to the following restrictions:
- //
- // 1. The origin of this software must not be misrepresented; you must not
- // claim that you wrote the original software. If you use this software
- // in a product, an acknowledgment in the product documentation would be
- // appreciated but is not required.
- // 2. Altered source versions must be plainly marked as such, and must not be
- // misrepresented as being the original software.
- // 3. This notice may not be removed or altered from any source distribution.
- var utils = require('../utils/common');
- /* Public constants ==========================================================*/
- /* ===========================================================================*/
- //var Z_FILTERED = 1;
- //var Z_HUFFMAN_ONLY = 2;
- //var Z_RLE = 3;
- var Z_FIXED = 4;
- //var Z_DEFAULT_STRATEGY = 0;
- /* Possible values of the data_type field (though see inflate()) */
- var Z_BINARY = 0;
- var Z_TEXT = 1;
- //var Z_ASCII = 1; // = Z_TEXT
- var Z_UNKNOWN = 2;
- /*============================================================================*/
- function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
- // From zutil.h
- var STORED_BLOCK = 0;
- var STATIC_TREES = 1;
- var DYN_TREES = 2;
- /* The three kinds of block type */
- var MIN_MATCH = 3;
- var MAX_MATCH = 258;
- /* The minimum and maximum match lengths */
- // From deflate.h
- /* ===========================================================================
- * Internal compression state.
- */
- var LENGTH_CODES = 29;
- /* number of length codes, not counting the special END_BLOCK code */
- var LITERALS = 256;
- /* number of literal bytes 0..255 */
- var L_CODES = LITERALS + 1 + LENGTH_CODES;
- /* number of Literal or Length codes, including the END_BLOCK code */
- var D_CODES = 30;
- /* number of distance codes */
- var BL_CODES = 19;
- /* number of codes used to transfer the bit lengths */
- var HEAP_SIZE = 2 * L_CODES + 1;
- /* maximum heap size */
- var MAX_BITS = 15;
- /* All codes must not exceed MAX_BITS bits */
- var Buf_size = 16;
- /* size of bit buffer in bi_buf */
- /* ===========================================================================
- * Constants
- */
- var MAX_BL_BITS = 7;
- /* Bit length codes must not exceed MAX_BL_BITS bits */
- var END_BLOCK = 256;
- /* end of block literal code */
- var REP_3_6 = 16;
- /* repeat previous bit length 3-6 times (2 bits of repeat count) */
- var REPZ_3_10 = 17;
- /* repeat a zero length 3-10 times (3 bits of repeat count) */
- var REPZ_11_138 = 18;
- /* repeat a zero length 11-138 times (7 bits of repeat count) */
- /* eslint-disable comma-spacing,array-bracket-spacing */
- var extra_lbits = /* extra bits for each length code */
- [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
- var extra_dbits = /* extra bits for each distance code */
- [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
- var extra_blbits = /* extra bits for each bit length code */
- [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
- var bl_order =
- [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
- /* eslint-enable comma-spacing,array-bracket-spacing */
- /* The lengths of the bit length codes are sent in order of decreasing
- * probability, to avoid transmitting the lengths for unused bit length codes.
- */
- /* ===========================================================================
- * Local data. These are initialized only once.
- */
- // We pre-fill arrays with 0 to avoid uninitialized gaps
- var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
- // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
- var static_ltree = new Array((L_CODES + 2) * 2);
- zero(static_ltree);
- /* The static literal tree. Since the bit lengths are imposed, there is no
- * need for the L_CODES extra codes used during heap construction. However
- * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
- * below).
- */
- var static_dtree = new Array(D_CODES * 2);
- zero(static_dtree);
- /* The static distance tree. (Actually a trivial tree since all codes use
- * 5 bits.)
- */
- var _dist_code = new Array(DIST_CODE_LEN);
- zero(_dist_code);
- /* Distance codes. The first 256 values correspond to the distances
- * 3 .. 258, the last 256 values correspond to the top 8 bits of
- * the 15 bit distances.
- */
- var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
- zero(_length_code);
- /* length code for each normalized match length (0 == MIN_MATCH) */
- var base_length = new Array(LENGTH_CODES);
- zero(base_length);
- /* First normalized length for each code (0 = MIN_MATCH) */
- var base_dist = new Array(D_CODES);
- zero(base_dist);
- /* First normalized distance for each code (0 = distance of 1) */
- function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
- this.static_tree = static_tree; /* static tree or NULL */
- this.extra_bits = extra_bits; /* extra bits for each code or NULL */
- this.extra_base = extra_base; /* base index for extra_bits */
- this.elems = elems; /* max number of elements in the tree */
- this.max_length = max_length; /* max bit length for the codes */
- // show if `static_tree` has data or dummy - needed for monomorphic objects
- this.has_stree = static_tree && static_tree.length;
- }
- var static_l_desc;
- var static_d_desc;
- var static_bl_desc;
- function TreeDesc(dyn_tree, stat_desc) {
- this.dyn_tree = dyn_tree; /* the dynamic tree */
- this.max_code = 0; /* largest code with non zero frequency */
- this.stat_desc = stat_desc; /* the corresponding static tree */
- }
- function d_code(dist) {
- return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
- }
- /* ===========================================================================
- * Output a short LSB first on the stream.
- * IN assertion: there is enough room in pendingBuf.
- */
- function put_short(s, w) {
- // put_byte(s, (uch)((w) & 0xff));
- // put_byte(s, (uch)((ush)(w) >> 8));
- s.pending_buf[s.pending++] = (w) & 0xff;
- s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
- }
- /* ===========================================================================
- * Send a value on a given number of bits.
- * IN assertion: length <= 16 and value fits in length bits.
- */
- function send_bits(s, value, length) {
- if (s.bi_valid > (Buf_size - length)) {
- s.bi_buf |= (value << s.bi_valid) & 0xffff;
- put_short(s, s.bi_buf);
- s.bi_buf = value >> (Buf_size - s.bi_valid);
- s.bi_valid += length - Buf_size;
- } else {
- s.bi_buf |= (value << s.bi_valid) & 0xffff;
- s.bi_valid += length;
- }
- }
- function send_code(s, c, tree) {
- send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
- }
- /* ===========================================================================
- * Reverse the first len bits of a code, using straightforward code (a faster
- * method would use a table)
- * IN assertion: 1 <= len <= 15
- */
- function bi_reverse(code, len) {
- var res = 0;
- do {
- res |= code & 1;
- code >>>= 1;
- res <<= 1;
- } while (--len > 0);
- return res >>> 1;
- }
- /* ===========================================================================
- * Flush the bit buffer, keeping at most 7 bits in it.
- */
- function bi_flush(s) {
- if (s.bi_valid === 16) {
- put_short(s, s.bi_buf);
- s.bi_buf = 0;
- s.bi_valid = 0;
- } else if (s.bi_valid >= 8) {
- s.pending_buf[s.pending++] = s.bi_buf & 0xff;
- s.bi_buf >>= 8;
- s.bi_valid -= 8;
- }
- }
- /* ===========================================================================
- * Compute the optimal bit lengths for a tree and update the total bit length
- * for the current block.
- * IN assertion: the fields freq and dad are set, heap[heap_max] and
- * above are the tree nodes sorted by increasing frequency.
- * OUT assertions: the field len is set to the optimal bit length, the
- * array bl_count contains the frequencies for each bit length.
- * The length opt_len is updated; static_len is also updated if stree is
- * not null.
- */
- function gen_bitlen(s, desc)
- // deflate_state *s;
- // tree_desc *desc; /* the tree descriptor */
- {
- var tree = desc.dyn_tree;
- var max_code = desc.max_code;
- var stree = desc.stat_desc.static_tree;
- var has_stree = desc.stat_desc.has_stree;
- var extra = desc.stat_desc.extra_bits;
- var base = desc.stat_desc.extra_base;
- var max_length = desc.stat_desc.max_length;
- var h; /* heap index */
- var n, m; /* iterate over the tree elements */
- var bits; /* bit length */
- var xbits; /* extra bits */
- var f; /* frequency */
- var overflow = 0; /* number of elements with bit length too large */
- for (bits = 0; bits <= MAX_BITS; bits++) {
- s.bl_count[bits] = 0;
- }
- /* In a first pass, compute the optimal bit lengths (which may
- * overflow in the case of the bit length tree).
- */
- tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
- for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
- n = s.heap[h];
- bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
- if (bits > max_length) {
- bits = max_length;
- overflow++;
- }
- tree[n * 2 + 1]/*.Len*/ = bits;
- /* We overwrite tree[n].Dad which is no longer needed */
- if (n > max_code) { continue; } /* not a leaf node */
- s.bl_count[bits]++;
- xbits = 0;
- if (n >= base) {
- xbits = extra[n - base];
- }
- f = tree[n * 2]/*.Freq*/;
- s.opt_len += f * (bits + xbits);
- if (has_stree) {
- s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
- }
- }
- if (overflow === 0) { return; }
- // Trace((stderr,"\nbit length overflow\n"));
- /* This happens for example on obj2 and pic of the Calgary corpus */
- /* Find the first bit length which could increase: */
- do {
- bits = max_length - 1;
- while (s.bl_count[bits] === 0) { bits--; }
- s.bl_count[bits]--; /* move one leaf down the tree */
- s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
- s.bl_count[max_length]--;
- /* The brother of the overflow item also moves one step up,
- * but this does not affect bl_count[max_length]
- */
- overflow -= 2;
- } while (overflow > 0);
- /* Now recompute all bit lengths, scanning in increasing frequency.
- * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
- * lengths instead of fixing only the wrong ones. This idea is taken
- * from 'ar' written by Haruhiko Okumura.)
- */
- for (bits = max_length; bits !== 0; bits--) {
- n = s.bl_count[bits];
- while (n !== 0) {
- m = s.heap[--h];
- if (m > max_code) { continue; }
- if (tree[m * 2 + 1]/*.Len*/ !== bits) {
- // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
- s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
- tree[m * 2 + 1]/*.Len*/ = bits;
- }
- n--;
- }
- }
- }
- /* ===========================================================================
- * Generate the codes for a given tree and bit counts (which need not be
- * optimal).
- * IN assertion: the array bl_count contains the bit length statistics for
- * the given tree and the field len is set for all tree elements.
- * OUT assertion: the field code is set for all tree elements of non
- * zero code length.
- */
- function gen_codes(tree, max_code, bl_count)
- // ct_data *tree; /* the tree to decorate */
- // int max_code; /* largest code with non zero frequency */
- // ushf *bl_count; /* number of codes at each bit length */
- {
- var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
- var code = 0; /* running code value */
- var bits; /* bit index */
- var n; /* code index */
- /* The distribution counts are first used to generate the code values
- * without bit reversal.
- */
- for (bits = 1; bits <= MAX_BITS; bits++) {
- next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
- }
- /* Check that the bit counts in bl_count are consistent. The last code
- * must be all ones.
- */
- //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
- // "inconsistent bit counts");
- //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
- for (n = 0; n <= max_code; n++) {
- var len = tree[n * 2 + 1]/*.Len*/;
- if (len === 0) { continue; }
- /* Now reverse the bits */
- tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
- //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
- // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
- }
- }
- /* ===========================================================================
- * Initialize the various 'constant' tables.
- */
- function tr_static_init() {
- var n; /* iterates over tree elements */
- var bits; /* bit counter */
- var length; /* length value */
- var code; /* code value */
- var dist; /* distance index */
- var bl_count = new Array(MAX_BITS + 1);
- /* number of codes at each bit length for an optimal tree */
- // do check in _tr_init()
- //if (static_init_done) return;
- /* For some embedded targets, global variables are not initialized: */
- /*#ifdef NO_INIT_GLOBAL_POINTERS
- static_l_desc.static_tree = static_ltree;
- static_l_desc.extra_bits = extra_lbits;
- static_d_desc.static_tree = static_dtree;
- static_d_desc.extra_bits = extra_dbits;
- static_bl_desc.extra_bits = extra_blbits;
- #endif*/
- /* Initialize the mapping length (0..255) -> length code (0..28) */
- length = 0;
- for (code = 0; code < LENGTH_CODES - 1; code++) {
- base_length[code] = length;
- for (n = 0; n < (1 << extra_lbits[code]); n++) {
- _length_code[length++] = code;
- }
- }
- //Assert (length == 256, "tr_static_init: length != 256");
- /* Note that the length 255 (match length 258) can be represented
- * in two different ways: code 284 + 5 bits or code 285, so we
- * overwrite length_code[255] to use the best encoding:
- */
- _length_code[length - 1] = code;
- /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
- dist = 0;
- for (code = 0; code < 16; code++) {
- base_dist[code] = dist;
- for (n = 0; n < (1 << extra_dbits[code]); n++) {
- _dist_code[dist++] = code;
- }
- }
- //Assert (dist == 256, "tr_static_init: dist != 256");
- dist >>= 7; /* from now on, all distances are divided by 128 */
- for (; code < D_CODES; code++) {
- base_dist[code] = dist << 7;
- for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
- _dist_code[256 + dist++] = code;
- }
- }
- //Assert (dist == 256, "tr_static_init: 256+dist != 512");
- /* Construct the codes of the static literal tree */
- for (bits = 0; bits <= MAX_BITS; bits++) {
- bl_count[bits] = 0;
- }
- n = 0;
- while (n <= 143) {
- static_ltree[n * 2 + 1]/*.Len*/ = 8;
- n++;
- bl_count[8]++;
- }
- while (n <= 255) {
- static_ltree[n * 2 + 1]/*.Len*/ = 9;
- n++;
- bl_count[9]++;
- }
- while (n <= 279) {
- static_ltree[n * 2 + 1]/*.Len*/ = 7;
- n++;
- bl_count[7]++;
- }
- while (n <= 287) {
- static_ltree[n * 2 + 1]/*.Len*/ = 8;
- n++;
- bl_count[8]++;
- }
- /* Codes 286 and 287 do not exist, but we must include them in the
- * tree construction to get a canonical Huffman tree (longest code
- * all ones)
- */
- gen_codes(static_ltree, L_CODES + 1, bl_count);
- /* The static distance tree is trivial: */
- for (n = 0; n < D_CODES; n++) {
- static_dtree[n * 2 + 1]/*.Len*/ = 5;
- static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
- }
- // Now data ready and we can init static trees
- static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
- static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
- static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
- //static_init_done = true;
- }
- /* ===========================================================================
- * Initialize a new block.
- */
- function init_block(s) {
- var n; /* iterates over tree elements */
- /* Initialize the trees. */
- for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
- for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
- for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
- s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
- s.opt_len = s.static_len = 0;
- s.last_lit = s.matches = 0;
- }
- /* ===========================================================================
- * Flush the bit buffer and align the output on a byte boundary
- */
- function bi_windup(s)
- {
- if (s.bi_valid > 8) {
- put_short(s, s.bi_buf);
- } else if (s.bi_valid > 0) {
- //put_byte(s, (Byte)s->bi_buf);
- s.pending_buf[s.pending++] = s.bi_buf;
- }
- s.bi_buf = 0;
- s.bi_valid = 0;
- }
- /* ===========================================================================
- * Copy a stored block, storing first the length and its
- * one's complement if requested.
- */
- function copy_block(s, buf, len, header)
- //DeflateState *s;
- //charf *buf; /* the input data */
- //unsigned len; /* its length */
- //int header; /* true if block header must be written */
- {
- bi_windup(s); /* align on byte boundary */
- if (header) {
- put_short(s, len);
- put_short(s, ~len);
- }
- // while (len--) {
- // put_byte(s, *buf++);
- // }
- utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
- s.pending += len;
- }
- /* ===========================================================================
- * Compares to subtrees, using the tree depth as tie breaker when
- * the subtrees have equal frequency. This minimizes the worst case length.
- */
- function smaller(tree, n, m, depth) {
- var _n2 = n * 2;
- var _m2 = m * 2;
- return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
- (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
- }
- /* ===========================================================================
- * Restore the heap property by moving down the tree starting at node k,
- * exchanging a node with the smallest of its two sons if necessary, stopping
- * when the heap property is re-established (each father smaller than its
- * two sons).
- */
- function pqdownheap(s, tree, k)
- // deflate_state *s;
- // ct_data *tree; /* the tree to restore */
- // int k; /* node to move down */
- {
- var v = s.heap[k];
- var j = k << 1; /* left son of k */
- while (j <= s.heap_len) {
- /* Set j to the smallest of the two sons: */
- if (j < s.heap_len &&
- smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
- j++;
- }
- /* Exit if v is smaller than both sons */
- if (smaller(tree, v, s.heap[j], s.depth)) { break; }
- /* Exchange v with the smallest son */
- s.heap[k] = s.heap[j];
- k = j;
- /* And continue down the tree, setting j to the left son of k */
- j <<= 1;
- }
- s.heap[k] = v;
- }
- // inlined manually
- // var SMALLEST = 1;
- /* ===========================================================================
- * Send the block data compressed using the given Huffman trees
- */
- function compress_block(s, ltree, dtree)
- // deflate_state *s;
- // const ct_data *ltree; /* literal tree */
- // const ct_data *dtree; /* distance tree */
- {
- var dist; /* distance of matched string */
- var lc; /* match length or unmatched char (if dist == 0) */
- var lx = 0; /* running index in l_buf */
- var code; /* the code to send */
- var extra; /* number of extra bits to send */
- if (s.last_lit !== 0) {
- do {
- dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
- lc = s.pending_buf[s.l_buf + lx];
- lx++;
- if (dist === 0) {
- send_code(s, lc, ltree); /* send a literal byte */
- //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
- } else {
- /* Here, lc is the match length - MIN_MATCH */
- code = _length_code[lc];
- send_code(s, code + LITERALS + 1, ltree); /* send the length code */
- extra = extra_lbits[code];
- if (extra !== 0) {
- lc -= base_length[code];
- send_bits(s, lc, extra); /* send the extra length bits */
- }
- dist--; /* dist is now the match distance - 1 */
- code = d_code(dist);
- //Assert (code < D_CODES, "bad d_code");
- send_code(s, code, dtree); /* send the distance code */
- extra = extra_dbits[code];
- if (extra !== 0) {
- dist -= base_dist[code];
- send_bits(s, dist, extra); /* send the extra distance bits */
- }
- } /* literal or match pair ? */
- /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
- //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
- // "pendingBuf overflow");
- } while (lx < s.last_lit);
- }
- send_code(s, END_BLOCK, ltree);
- }
- /* ===========================================================================
- * Construct one Huffman tree and assigns the code bit strings and lengths.
- * Update the total bit length for the current block.
- * IN assertion: the field freq is set for all tree elements.
- * OUT assertions: the fields len and code are set to the optimal bit length
- * and corresponding code. The length opt_len is updated; static_len is
- * also updated if stree is not null. The field max_code is set.
- */
- function build_tree(s, desc)
- // deflate_state *s;
- // tree_desc *desc; /* the tree descriptor */
- {
- var tree = desc.dyn_tree;
- var stree = desc.stat_desc.static_tree;
- var has_stree = desc.stat_desc.has_stree;
- var elems = desc.stat_desc.elems;
- var n, m; /* iterate over heap elements */
- var max_code = -1; /* largest code with non zero frequency */
- var node; /* new node being created */
- /* Construct the initial heap, with least frequent element in
- * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
- * heap[0] is not used.
- */
- s.heap_len = 0;
- s.heap_max = HEAP_SIZE;
- for (n = 0; n < elems; n++) {
- if (tree[n * 2]/*.Freq*/ !== 0) {
- s.heap[++s.heap_len] = max_code = n;
- s.depth[n] = 0;
- } else {
- tree[n * 2 + 1]/*.Len*/ = 0;
- }
- }
- /* The pkzip format requires that at least one distance code exists,
- * and that at least one bit should be sent even if there is only one
- * possible code. So to avoid special checks later on we force at least
- * two codes of non zero frequency.
- */
- while (s.heap_len < 2) {
- node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
- tree[node * 2]/*.Freq*/ = 1;
- s.depth[node] = 0;
- s.opt_len--;
- if (has_stree) {
- s.static_len -= stree[node * 2 + 1]/*.Len*/;
- }
- /* node is 0 or 1 so it does not have extra bits */
- }
- desc.max_code = max_code;
- /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
- * establish sub-heaps of increasing lengths:
- */
- for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
- /* Construct the Huffman tree by repeatedly combining the least two
- * frequent nodes.
- */
- node = elems; /* next internal node of the tree */
- do {
- //pqremove(s, tree, n); /* n = node of least frequency */
- /*** pqremove ***/
- n = s.heap[1/*SMALLEST*/];
- s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
- pqdownheap(s, tree, 1/*SMALLEST*/);
- /***/
- m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
- s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
- s.heap[--s.heap_max] = m;
- /* Create a new node father of n and m */
- tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
- s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
- tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
- /* and insert the new node in the heap */
- s.heap[1/*SMALLEST*/] = node++;
- pqdownheap(s, tree, 1/*SMALLEST*/);
- } while (s.heap_len >= 2);
- s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
- /* At this point, the fields freq and dad are set. We can now
- * generate the bit lengths.
- */
- gen_bitlen(s, desc);
- /* The field len is now set, we can generate the bit codes */
- gen_codes(tree, max_code, s.bl_count);
- }
- /* ===========================================================================
- * Scan a literal or distance tree to determine the frequencies of the codes
- * in the bit length tree.
- */
- function scan_tree(s, tree, max_code)
- // deflate_state *s;
- // ct_data *tree; /* the tree to be scanned */
- // int max_code; /* and its largest code of non zero frequency */
- {
- var n; /* iterates over all tree elements */
- var prevlen = -1; /* last emitted length */
- var curlen; /* length of current code */
- var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
- var count = 0; /* repeat count of the current code */
- var max_count = 7; /* max repeat count */
- var min_count = 4; /* min repeat count */
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- }
- tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
- for (n = 0; n <= max_code; n++) {
- curlen = nextlen;
- nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
- if (++count < max_count && curlen === nextlen) {
- continue;
- } else if (count < min_count) {
- s.bl_tree[curlen * 2]/*.Freq*/ += count;
- } else if (curlen !== 0) {
- if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
- s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
- } else if (count <= 10) {
- s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
- } else {
- s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
- }
- count = 0;
- prevlen = curlen;
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- } else if (curlen === nextlen) {
- max_count = 6;
- min_count = 3;
- } else {
- max_count = 7;
- min_count = 4;
- }
- }
- }
- /* ===========================================================================
- * Send a literal or distance tree in compressed form, using the codes in
- * bl_tree.
- */
- function send_tree(s, tree, max_code)
- // deflate_state *s;
- // ct_data *tree; /* the tree to be scanned */
- // int max_code; /* and its largest code of non zero frequency */
- {
- var n; /* iterates over all tree elements */
- var prevlen = -1; /* last emitted length */
- var curlen; /* length of current code */
- var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
- var count = 0; /* repeat count of the current code */
- var max_count = 7; /* max repeat count */
- var min_count = 4; /* min repeat count */
- /* tree[max_code+1].Len = -1; */ /* guard already set */
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- }
- for (n = 0; n <= max_code; n++) {
- curlen = nextlen;
- nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
- if (++count < max_count && curlen === nextlen) {
- continue;
- } else if (count < min_count) {
- do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
- } else if (curlen !== 0) {
- if (curlen !== prevlen) {
- send_code(s, curlen, s.bl_tree);
- count--;
- }
- //Assert(count >= 3 && count <= 6, " 3_6?");
- send_code(s, REP_3_6, s.bl_tree);
- send_bits(s, count - 3, 2);
- } else if (count <= 10) {
- send_code(s, REPZ_3_10, s.bl_tree);
- send_bits(s, count - 3, 3);
- } else {
- send_code(s, REPZ_11_138, s.bl_tree);
- send_bits(s, count - 11, 7);
- }
- count = 0;
- prevlen = curlen;
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- } else if (curlen === nextlen) {
- max_count = 6;
- min_count = 3;
- } else {
- max_count = 7;
- min_count = 4;
- }
- }
- }
- /* ===========================================================================
- * Construct the Huffman tree for the bit lengths and return the index in
- * bl_order of the last bit length code to send.
- */
- function build_bl_tree(s) {
- var max_blindex; /* index of last bit length code of non zero freq */
- /* Determine the bit length frequencies for literal and distance trees */
- scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
- scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
- /* Build the bit length tree: */
- build_tree(s, s.bl_desc);
- /* opt_len now includes the length of the tree representations, except
- * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
- */
- /* Determine the number of bit length codes to send. The pkzip format
- * requires that at least 4 bit length codes be sent. (appnote.txt says
- * 3 but the actual value used is 4.)
- */
- for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
- if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
- break;
- }
- }
- /* Update opt_len to include the bit length tree and counts */
- s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
- //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
- // s->opt_len, s->static_len));
- return max_blindex;
- }
- /* ===========================================================================
- * Send the header for a block using dynamic Huffman trees: the counts, the
- * lengths of the bit length codes, the literal tree and the distance tree.
- * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
- */
- function send_all_trees(s, lcodes, dcodes, blcodes)
- // deflate_state *s;
- // int lcodes, dcodes, blcodes; /* number of codes for each tree */
- {
- var rank; /* index in bl_order */
- //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
- //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
- // "too many codes");
- //Tracev((stderr, "\nbl counts: "));
- send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
- send_bits(s, dcodes - 1, 5);
- send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
- for (rank = 0; rank < blcodes; rank++) {
- //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
- send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
- }
- //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
- send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
- //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
- send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
- //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
- }
- /* ===========================================================================
- * Check if the data type is TEXT or BINARY, using the following algorithm:
- * - TEXT if the two conditions below are satisfied:
- * a) There are no non-portable control characters belonging to the
- * "black list" (0..6, 14..25, 28..31).
- * b) There is at least one printable character belonging to the
- * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
- * - BINARY otherwise.
- * - The following partially-portable control characters form a
- * "gray list" that is ignored in this detection algorithm:
- * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
- * IN assertion: the fields Freq of dyn_ltree are set.
- */
- function detect_data_type(s) {
- /* black_mask is the bit mask of black-listed bytes
- * set bits 0..6, 14..25, and 28..31
- * 0xf3ffc07f = binary 11110011111111111100000001111111
- */
- var black_mask = 0xf3ffc07f;
- var n;
- /* Check for non-textual ("black-listed") bytes. */
- for (n = 0; n <= 31; n++, black_mask >>>= 1) {
- if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
- return Z_BINARY;
- }
- }
- /* Check for textual ("white-listed") bytes. */
- if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
- s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
- return Z_TEXT;
- }
- for (n = 32; n < LITERALS; n++) {
- if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
- return Z_TEXT;
- }
- }
- /* There are no "black-listed" or "white-listed" bytes:
- * this stream either is empty or has tolerated ("gray-listed") bytes only.
- */
- return Z_BINARY;
- }
- var static_init_done = false;
- /* ===========================================================================
- * Initialize the tree data structures for a new zlib stream.
- */
- function _tr_init(s)
- {
- if (!static_init_done) {
- tr_static_init();
- static_init_done = true;
- }
- s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
- s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
- s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
- s.bi_buf = 0;
- s.bi_valid = 0;
- /* Initialize the first block of the first file: */
- init_block(s);
- }
- /* ===========================================================================
- * Send a stored block
- */
- function _tr_stored_block(s, buf, stored_len, last)
- //DeflateState *s;
- //charf *buf; /* input block */
- //ulg stored_len; /* length of input block */
- //int last; /* one if this is the last block for a file */
- {
- send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
- copy_block(s, buf, stored_len, true); /* with header */
- }
- /* ===========================================================================
- * Send one empty static block to give enough lookahead for inflate.
- * This takes 10 bits, of which 7 may remain in the bit buffer.
- */
- function _tr_align(s) {
- send_bits(s, STATIC_TREES << 1, 3);
- send_code(s, END_BLOCK, static_ltree);
- bi_flush(s);
- }
- /* ===========================================================================
- * Determine the best encoding for the current block: dynamic trees, static
- * trees or store, and output the encoded block to the zip file.
- */
- function _tr_flush_block(s, buf, stored_len, last)
- //DeflateState *s;
- //charf *buf; /* input block, or NULL if too old */
- //ulg stored_len; /* length of input block */
- //int last; /* one if this is the last block for a file */
- {
- var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
- var max_blindex = 0; /* index of last bit length code of non zero freq */
- /* Build the Huffman trees unless a stored block is forced */
- if (s.level > 0) {
- /* Check if the file is binary or text */
- if (s.strm.data_type === Z_UNKNOWN) {
- s.strm.data_type = detect_data_type(s);
- }
- /* Construct the literal and distance trees */
- build_tree(s, s.l_desc);
- // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
- // s->static_len));
- build_tree(s, s.d_desc);
- // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
- // s->static_len));
- /* At this point, opt_len and static_len are the total bit lengths of
- * the compressed block data, excluding the tree representations.
- */
- /* Build the bit length tree for the above two trees, and get the index
- * in bl_order of the last bit length code to send.
- */
- max_blindex = build_bl_tree(s);
- /* Determine the best encoding. Compute the block lengths in bytes. */
- opt_lenb = (s.opt_len + 3 + 7) >>> 3;
- static_lenb = (s.static_len + 3 + 7) >>> 3;
- // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
- // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
- // s->last_lit));
- if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
- } else {
- // Assert(buf != (char*)0, "lost buf");
- opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
- }
- if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
- /* 4: two words for the lengths */
- /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
- * Otherwise we can't have processed more than WSIZE input bytes since
- * the last block flush, because compression would have been
- * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
- * transform a block into a stored block.
- */
- _tr_stored_block(s, buf, stored_len, last);
- } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
- send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
- compress_block(s, static_ltree, static_dtree);
- } else {
- send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
- send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
- compress_block(s, s.dyn_ltree, s.dyn_dtree);
- }
- // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
- /* The above check is made mod 2^32, for files larger than 512 MB
- * and uLong implemented on 32 bits.
- */
- init_block(s);
- if (last) {
- bi_windup(s);
- }
- // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
- // s->compressed_len-7*last));
- }
- /* ===========================================================================
- * Save the match info and tally the frequency counts. Return true if
- * the current block must be flushed.
- */
- function _tr_tally(s, dist, lc)
- // deflate_state *s;
- // unsigned dist; /* distance of matched string */
- // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
- {
- //var out_length, in_length, dcode;
- s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
- s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
- s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
- s.last_lit++;
- if (dist === 0) {
- /* lc is the unmatched char */
- s.dyn_ltree[lc * 2]/*.Freq*/++;
- } else {
- s.matches++;
- /* Here, lc is the match length - MIN_MATCH */
- dist--; /* dist = match distance - 1 */
- //Assert((ush)dist < (ush)MAX_DIST(s) &&
- // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
- // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
- s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
- s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
- }
- // (!) This block is disabled in zlib defaults,
- // don't enable it for binary compatibility
- //#ifdef TRUNCATE_BLOCK
- // /* Try to guess if it is profitable to stop the current block here */
- // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
- // /* Compute an upper bound for the compressed length */
- // out_length = s.last_lit*8;
- // in_length = s.strstart - s.block_start;
- //
- // for (dcode = 0; dcode < D_CODES; dcode++) {
- // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
- // }
- // out_length >>>= 3;
- // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
- // // s->last_lit, in_length, out_length,
- // // 100L - out_length*100L/in_length));
- // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
- // return true;
- // }
- // }
- //#endif
- return (s.last_lit === s.lit_bufsize - 1);
- /* We avoid equality with lit_bufsize because of wraparound at 64K
- * on 16 bit machines and because stored blocks are restricted to
- * 64K-1 bytes.
- */
- }
- exports._tr_init = _tr_init;
- exports._tr_stored_block = _tr_stored_block;
- exports._tr_flush_block = _tr_flush_block;
- exports._tr_tally = _tr_tally;
- exports._tr_align = _tr_align;
- },{"../utils/common":268}],280:[function(require,module,exports){
- arguments[4][45][0].apply(exports,arguments)
- },{"dup":45}],281:[function(require,module,exports){
- module.exports = function parseBMFontAscii(data) {
- if (!data)
- throw new Error('no data provided')
- data = data.toString().trim()
- var output = {
- pages: [],
- chars: [],
- kernings: []
- }
- var lines = data.split(/\r\n?|\n/g)
- if (lines.length === 0)
- throw new Error('no data in BMFont file')
- for (var i = 0; i < lines.length; i++) {
- var lineData = splitLine(lines[i], i)
- if (!lineData) //skip empty lines
- continue
- if (lineData.key === 'page') {
- if (typeof lineData.data.id !== 'number')
- throw new Error('malformed file at line ' + i + ' -- needs page id=N')
- if (typeof lineData.data.file !== 'string')
- throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
- output.pages[lineData.data.id] = lineData.data.file
- } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
- //... do nothing for these two ...
- } else if (lineData.key === 'char') {
- output.chars.push(lineData.data)
- } else if (lineData.key === 'kerning') {
- output.kernings.push(lineData.data)
- } else {
- output[lineData.key] = lineData.data
- }
- }
- return output
- }
- function splitLine(line, idx) {
- line = line.replace(/\t+/g, ' ').trim()
- if (!line)
- return null
- var space = line.indexOf(' ')
- if (space === -1)
- throw new Error("no named row at line " + idx)
- var key = line.substring(0, space)
- line = line.substring(space + 1)
- //clear "letter" field as it is non-standard and
- //requires additional complexity to parse " / = symbols
- line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
- line = line.split("=")
- line = line.map(function(str) {
- return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
- })
- var data = []
- for (var i = 0; i < line.length; i++) {
- var dt = line[i]
- if (i === 0) {
- data.push({
- key: dt[0],
- data: ""
- })
- } else if (i === line.length - 1) {
- data[data.length - 1].data = parseData(dt[0])
- } else {
- data[data.length - 1].data = parseData(dt[0])
- data.push({
- key: dt[1],
- data: ""
- })
- }
- }
- var out = {
- key: key,
- data: {}
- }
- data.forEach(function(v) {
- out.data[v.key] = v.data;
- })
- return out
- }
- function parseData(data) {
- if (!data || data.length === 0)
- return ""
- if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
- return data.substring(1, data.length - 1)
- if (data.indexOf(',') !== -1)
- return parseIntList(data)
- return parseInt(data, 10)
- }
- function parseIntList(data) {
- return data.split(',').map(function(val) {
- return parseInt(val, 10)
- })
- }
- },{}],282:[function(require,module,exports){
- var HEADER = [66, 77, 70]
- module.exports = function readBMFontBinary(buf) {
- if (buf.length < 6)
- throw new Error('invalid buffer length for BMFont')
- var header = HEADER.every(function(byte, i) {
- return buf.readUInt8(i) === byte
- })
- if (!header)
- throw new Error('BMFont missing BMF byte header')
- var i = 3
- var vers = buf.readUInt8(i++)
- if (vers > 3)
- throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
-
- var target = { kernings: [], chars: [] }
- for (var b=0; b<5; b++)
- i += readBlock(target, buf, i)
- return target
- }
- function readBlock(target, buf, i) {
- if (i > buf.length-1)
- return 0
- var blockID = buf.readUInt8(i++)
- var blockSize = buf.readInt32LE(i)
- i += 4
- switch(blockID) {
- case 1:
- target.info = readInfo(buf, i)
- break
- case 2:
- target.common = readCommon(buf, i)
- break
- case 3:
- target.pages = readPages(buf, i, blockSize)
- break
- case 4:
- target.chars = readChars(buf, i, blockSize)
- break
- case 5:
- target.kernings = readKernings(buf, i, blockSize)
- break
- }
- return 5 + blockSize
- }
- function readInfo(buf, i) {
- var info = {}
- info.size = buf.readInt16LE(i)
- var bitField = buf.readUInt8(i+2)
- info.smooth = (bitField >> 7) & 1
- info.unicode = (bitField >> 6) & 1
- info.italic = (bitField >> 5) & 1
- info.bold = (bitField >> 4) & 1
-
- //fixedHeight is only mentioned in binary spec
- if ((bitField >> 3) & 1)
- info.fixedHeight = 1
-
- info.charset = buf.readUInt8(i+3) || ''
- info.stretchH = buf.readUInt16LE(i+4)
- info.aa = buf.readUInt8(i+6)
- info.padding = [
- buf.readInt8(i+7),
- buf.readInt8(i+8),
- buf.readInt8(i+9),
- buf.readInt8(i+10)
- ]
- info.spacing = [
- buf.readInt8(i+11),
- buf.readInt8(i+12)
- ]
- info.outline = buf.readUInt8(i+13)
- info.face = readStringNT(buf, i+14)
- return info
- }
- function readCommon(buf, i) {
- var common = {}
- common.lineHeight = buf.readUInt16LE(i)
- common.base = buf.readUInt16LE(i+2)
- common.scaleW = buf.readUInt16LE(i+4)
- common.scaleH = buf.readUInt16LE(i+6)
- common.pages = buf.readUInt16LE(i+8)
- var bitField = buf.readUInt8(i+10)
- common.packed = 0
- common.alphaChnl = buf.readUInt8(i+11)
- common.redChnl = buf.readUInt8(i+12)
- common.greenChnl = buf.readUInt8(i+13)
- common.blueChnl = buf.readUInt8(i+14)
- return common
- }
- function readPages(buf, i, size) {
- var pages = []
- var text = readNameNT(buf, i)
- var len = text.length+1
- var count = size / len
- for (var c=0; c<count; c++) {
- pages[c] = buf.slice(i, i+text.length).toString('utf8')
- i += len
- }
- return pages
- }
- function readChars(buf, i, blockSize) {
- var chars = []
- var count = blockSize / 20
- for (var c=0; c<count; c++) {
- var char = {}
- var off = c*20
- char.id = buf.readUInt32LE(i + 0 + off)
- char.x = buf.readUInt16LE(i + 4 + off)
- char.y = buf.readUInt16LE(i + 6 + off)
- char.width = buf.readUInt16LE(i + 8 + off)
- char.height = buf.readUInt16LE(i + 10 + off)
- char.xoffset = buf.readInt16LE(i + 12 + off)
- char.yoffset = buf.readInt16LE(i + 14 + off)
- char.xadvance = buf.readInt16LE(i + 16 + off)
- char.page = buf.readUInt8(i + 18 + off)
- char.chnl = buf.readUInt8(i + 19 + off)
- chars[c] = char
- }
- return chars
- }
- function readKernings(buf, i, blockSize) {
- var kernings = []
- var count = blockSize / 10
- for (var c=0; c<count; c++) {
- var kern = {}
- var off = c*10
- kern.first = buf.readUInt32LE(i + 0 + off)
- kern.second = buf.readUInt32LE(i + 4 + off)
- kern.amount = buf.readInt16LE(i + 8 + off)
- kernings[c] = kern
- }
- return kernings
- }
- function readNameNT(buf, offset) {
- var pos=offset
- for (; pos<buf.length; pos++) {
- if (buf[pos] === 0x00)
- break
- }
- return buf.slice(offset, pos)
- }
- function readStringNT(buf, offset) {
- return readNameNT(buf, offset).toString('utf8')
- }
- },{}],283:[function(require,module,exports){
- var parseAttributes = require('./parse-attribs')
- var parseFromString = require('xml-parse-from-string')
- //In some cases element.attribute.nodeName can return
- //all lowercase values.. so we need to map them to the correct
- //case
- var NAME_MAP = {
- scaleh: 'scaleH',
- scalew: 'scaleW',
- stretchh: 'stretchH',
- lineheight: 'lineHeight',
- alphachnl: 'alphaChnl',
- redchnl: 'redChnl',
- greenchnl: 'greenChnl',
- bluechnl: 'blueChnl'
- }
- module.exports = function parse(data) {
- data = data.toString()
-
- var xmlRoot = parseFromString(data)
- var output = {
- pages: [],
- chars: [],
- kernings: []
- }
- //get config settings
- ;['info', 'common'].forEach(function(key) {
- var element = xmlRoot.getElementsByTagName(key)[0]
- if (element)
- output[key] = parseAttributes(getAttribs(element))
- })
- //get page info
- var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
- if (!pageRoot)
- throw new Error('malformed file -- no <pages> element')
- var pages = pageRoot.getElementsByTagName('page')
- for (var i=0; i<pages.length; i++) {
- var p = pages[i]
- var id = parseInt(p.getAttribute('id'), 10)
- var file = p.getAttribute('file')
- if (isNaN(id))
- throw new Error('malformed file -- page "id" attribute is NaN')
- if (!file)
- throw new Error('malformed file -- needs page "file" attribute')
- output.pages[parseInt(id, 10)] = file
- }
- //get kernings / chars
- ;['chars', 'kernings'].forEach(function(key) {
- var element = xmlRoot.getElementsByTagName(key)[0]
- if (!element)
- return
- var childTag = key.substring(0, key.length-1)
- var children = element.getElementsByTagName(childTag)
- for (var i=0; i<children.length; i++) {
- var child = children[i]
- output[key].push(parseAttributes(getAttribs(child)))
- }
- })
- return output
- }
- function getAttribs(element) {
- var attribs = getAttribList(element)
- return attribs.reduce(function(dict, attrib) {
- var key = mapName(attrib.nodeName)
- dict[key] = attrib.nodeValue
- return dict
- }, {})
- }
- function getAttribList(element) {
- //IE8+ and modern browsers
- var attribs = []
- for (var i=0; i<element.attributes.length; i++)
- attribs.push(element.attributes[i])
- return attribs
- }
- function mapName(nodeName) {
- return NAME_MAP[nodeName.toLowerCase()] || nodeName
- }
- },{"./parse-attribs":284,"xml-parse-from-string":367}],284:[function(require,module,exports){
- //Some versions of GlyphDesigner have a typo
- //that causes some bugs with parsing.
- //Need to confirm with recent version of the software
- //to see whether this is still an issue or not.
- var GLYPH_DESIGNER_ERROR = 'chasrset'
- module.exports = function parseAttributes(obj) {
- if (GLYPH_DESIGNER_ERROR in obj) {
- obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
- delete obj[GLYPH_DESIGNER_ERROR]
- }
- for (var k in obj) {
- if (k === 'face' || k === 'charset')
- continue
- else if (k === 'padding' || k === 'spacing')
- obj[k] = parseIntList(obj[k])
- else
- obj[k] = parseInt(obj[k], 10)
- }
- return obj
- }
- function parseIntList(data) {
- return data.split(',').map(function(val) {
- return parseInt(val, 10)
- })
- }
- },{}],285:[function(require,module,exports){
- var trim = require('trim')
- , forEach = require('for-each')
- , isArray = function(arg) {
- return Object.prototype.toString.call(arg) === '[object Array]';
- }
- module.exports = function (headers) {
- if (!headers)
- return {}
- var result = {}
- forEach(
- trim(headers).split('\n')
- , function (row) {
- var index = row.indexOf(':')
- , key = trim(row.slice(0, index)).toLowerCase()
- , value = trim(row.slice(index + 1))
- if (typeof(result[key]) === 'undefined') {
- result[key] = value
- } else if (isArray(result[key])) {
- result[key].push(value)
- } else {
- result[key] = [ result[key], value ]
- }
- }
- )
- return result
- }
- },{"for-each":250,"trim":358}],286:[function(require,module,exports){
- (function (process){
- // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
- // backported and transplited with Babel, with backwards-compat fixes
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // resolves . and .. elements in a path array with directory names there
- // must be no slashes, empty elements, or device names (c:\) in the array
- // (so also no leading and trailing slashes - it does not distinguish
- // relative and absolute paths)
- function normalizeArray(parts, allowAboveRoot) {
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = parts.length - 1; i >= 0; i--) {
- var last = parts[i];
- if (last === '.') {
- parts.splice(i, 1);
- } else if (last === '..') {
- parts.splice(i, 1);
- up++;
- } else if (up) {
- parts.splice(i, 1);
- up--;
- }
- }
- // if the path is allowed to go above the root, restore leading ..s
- if (allowAboveRoot) {
- for (; up--; up) {
- parts.unshift('..');
- }
- }
- return parts;
- }
- // path.resolve([from ...], to)
- // posix version
- exports.resolve = function() {
- var resolvedPath = '',
- resolvedAbsolute = false;
- for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
- var path = (i >= 0) ? arguments[i] : process.cwd();
- // Skip empty and invalid entries
- if (typeof path !== 'string') {
- throw new TypeError('Arguments to path.resolve must be strings');
- } else if (!path) {
- continue;
- }
- resolvedPath = path + '/' + resolvedPath;
- resolvedAbsolute = path.charAt(0) === '/';
- }
- // At this point the path should be resolved to a full absolute path, but
- // handle relative paths to be safe (might happen when process.cwd() fails)
- // Normalize the path
- resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
- return !!p;
- }), !resolvedAbsolute).join('/');
- return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
- };
- // path.normalize(path)
- // posix version
- exports.normalize = function(path) {
- var isAbsolute = exports.isAbsolute(path),
- trailingSlash = substr(path, -1) === '/';
- // Normalize the path
- path = normalizeArray(filter(path.split('/'), function(p) {
- return !!p;
- }), !isAbsolute).join('/');
- if (!path && !isAbsolute) {
- path = '.';
- }
- if (path && trailingSlash) {
- path += '/';
- }
- return (isAbsolute ? '/' : '') + path;
- };
- // posix version
- exports.isAbsolute = function(path) {
- return path.charAt(0) === '/';
- };
- // posix version
- exports.join = function() {
- var paths = Array.prototype.slice.call(arguments, 0);
- return exports.normalize(filter(paths, function(p, index) {
- if (typeof p !== 'string') {
- throw new TypeError('Arguments to path.join must be strings');
- }
- return p;
- }).join('/'));
- };
- // path.relative(from, to)
- // posix version
- exports.relative = function(from, to) {
- from = exports.resolve(from).substr(1);
- to = exports.resolve(to).substr(1);
- function trim(arr) {
- var start = 0;
- for (; start < arr.length; start++) {
- if (arr[start] !== '') break;
- }
- var end = arr.length - 1;
- for (; end >= 0; end--) {
- if (arr[end] !== '') break;
- }
- if (start > end) return [];
- return arr.slice(start, end - start + 1);
- }
- var fromParts = trim(from.split('/'));
- var toParts = trim(to.split('/'));
- var length = Math.min(fromParts.length, toParts.length);
- var samePartsLength = length;
- for (var i = 0; i < length; i++) {
- if (fromParts[i] !== toParts[i]) {
- samePartsLength = i;
- break;
- }
- }
- var outputParts = [];
- for (var i = samePartsLength; i < fromParts.length; i++) {
- outputParts.push('..');
- }
- outputParts = outputParts.concat(toParts.slice(samePartsLength));
- return outputParts.join('/');
- };
- exports.sep = '/';
- exports.delimiter = ':';
- exports.dirname = function (path) {
- if (typeof path !== 'string') path = path + '';
- if (path.length === 0) return '.';
- var code = path.charCodeAt(0);
- var hasRoot = code === 47 /*/*/;
- var end = -1;
- var matchedSlash = true;
- for (var i = path.length - 1; i >= 1; --i) {
- code = path.charCodeAt(i);
- if (code === 47 /*/*/) {
- if (!matchedSlash) {
- end = i;
- break;
- }
- } else {
- // We saw the first non-path separator
- matchedSlash = false;
- }
- }
- if (end === -1) return hasRoot ? '/' : '.';
- if (hasRoot && end === 1) {
- // return '//';
- // Backwards-compat fix:
- return '/';
- }
- return path.slice(0, end);
- };
- function basename(path) {
- if (typeof path !== 'string') path = path + '';
- var start = 0;
- var end = -1;
- var matchedSlash = true;
- var i;
- for (i = path.length - 1; i >= 0; --i) {
- if (path.charCodeAt(i) === 47 /*/*/) {
- // If we reached a path separator that was not part of a set of path
- // separators at the end of the string, stop now
- if (!matchedSlash) {
- start = i + 1;
- break;
- }
- } else if (end === -1) {
- // We saw the first non-path separator, mark this as the end of our
- // path component
- matchedSlash = false;
- end = i + 1;
- }
- }
- if (end === -1) return '';
- return path.slice(start, end);
- }
- // Uses a mixed approach for backwards-compatibility, as ext behavior changed
- // in new Node.js versions, so only basename() above is backported here
- exports.basename = function (path, ext) {
- var f = basename(path);
- if (ext && f.substr(-1 * ext.length) === ext) {
- f = f.substr(0, f.length - ext.length);
- }
- return f;
- };
- exports.extname = function (path) {
- if (typeof path !== 'string') path = path + '';
- var startDot = -1;
- var startPart = 0;
- var end = -1;
- var matchedSlash = true;
- // Track the state of characters (if any) we see before our first dot and
- // after any path separator we find
- var preDotState = 0;
- for (var i = path.length - 1; i >= 0; --i) {
- var code = path.charCodeAt(i);
- if (code === 47 /*/*/) {
- // If we reached a path separator that was not part of a set of path
- // separators at the end of the string, stop now
- if (!matchedSlash) {
- startPart = i + 1;
- break;
- }
- continue;
- }
- if (end === -1) {
- // We saw the first non-path separator, mark this as the end of our
- // extension
- matchedSlash = false;
- end = i + 1;
- }
- if (code === 46 /*.*/) {
- // If this is our first dot, mark it as the start of our extension
- if (startDot === -1)
- startDot = i;
- else if (preDotState !== 1)
- preDotState = 1;
- } else if (startDot !== -1) {
- // We saw a non-dot and non-path separator before our dot, so we should
- // have a good chance at having a non-empty extension
- preDotState = -1;
- }
- }
- if (startDot === -1 || end === -1 ||
- // We saw a non-dot character immediately before the dot
- preDotState === 0 ||
- // The (right-most) trimmed path component is exactly '..'
- preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
- return '';
- }
- return path.slice(startDot, end);
- };
- function filter (xs, f) {
- if (xs.filter) return xs.filter(f);
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- if (f(xs[i], i, xs)) res.push(xs[i]);
- }
- return res;
- }
- // String.prototype.substr - negative index don't work in IE8
- var substr = 'ab'.substr(-1) === 'b'
- ? function (str, start, len) { return str.substr(start, len) }
- : function (str, start, len) {
- if (start < 0) start = str.length + start;
- return str.substr(start, len);
- }
- ;
- }).call(this,require('_process'))
- },{"_process":312}],287:[function(require,module,exports){
- (function (Buffer){
- 'use strict';var _typeof=typeof Symbol==='function'&&typeof Symbol.iterator==='symbol'?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==='function'&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj};var http=require('http');var https=require('https');var url=require('url');var qs=require('querystring');var zlib=require('zlib');var util=require('util');var phin=function phin(opts,cb){if(typeof opts!=='string'){if(!opts.hasOwnProperty('url')){throw new Error('Missing url option from options for request method.')}}var addr=(typeof opts==='undefined'?'undefined':_typeof(opts))==='object'?url.parse(opts.url):url.parse(opts);var options={'hostname':addr.hostname,'port':addr.port||(addr.protocol.toLowerCase()==='http:'?80:443),'path':addr.path,'method':'GET','headers':{},'auth':addr.auth||null,'parse':'none','stream':false};if((typeof opts==='undefined'?'undefined':_typeof(opts))==='object'){options=Object.assign(options,opts)}options.port=Number(options.port);if(options.hasOwnProperty('timeout'))delete options.timeout;if(options.compressed===true){options.headers['accept-encoding']='gzip, deflate'}if(opts.hasOwnProperty('form')){if(_typeof(opts.form)!=='object'){throw new Error('phin \'form\' option must be of type Object if present.')}var formDataString=qs.stringify(opts.form);options.headers['Content-Type']='application/x-www-form-urlencoded';options.headers['Content-Length']=Buffer.byteLength(formDataString);opts.data=formDataString}var req=void 0;var resHandler=function resHandler(res){var stream=res;if(options.compressed===true){if(res.headers['content-encoding']==='gzip'){stream=res.pipe(zlib.createGunzip())}else if(res.headers['content-encoding']==='deflate'){stream=res.pipe(zlib.createInflate())}}if(options.stream===true){res.stream=stream;cb(null,res)}else{res.body=new Buffer([]);stream.on('data',function(chunk){res.body=Buffer.concat([res.body,chunk])});stream.on('end',function(){if(cb){if(options.parse==='json'){try{res.body=JSON.parse(res.body.toString())}catch(err){cb('Invalid JSON received.',res);return}}cb(null,res)}})}};switch(addr.protocol.toLowerCase()){case'http:':req=http.request(options,resHandler);break;case'https:':req=https.request(options,resHandler);break;default:if(cb){cb(new Error('Invalid / unknown URL protocol. Expected HTTP or HTTPS.'),null)}return;}if(typeof opts.timeout==='number'){req.setTimeout(opts.timeout,function(){req.abort();cb(new Error('Timeout has been reached.'),null);cb=null})}req.on('error',function(err){if(cb){cb(err,null)}});if(opts.hasOwnProperty('data')){var postData=opts.data;if(!(opts.data instanceof Buffer)&&_typeof(opts.data)==='object'){var contentType=options.headers['content-type']||options.headers['Content-Type'];if(contentType==='application/x-www-form-urlencoded'){postData=qs.stringify(opts.data)}else{try{postData=JSON.stringify(opts.data)}catch(err){cb(new Error('Couldn\'t stringify object. (Likely due to a circular reference.)'),null)}}}req.write(postData)}req.end()};phin.promisified=function(opts,http){return new Promise(function(resolve,reject){phin(opts,function(err,res){if(err){reject(err)}else{resolve(res)}},http)})};if(util.promisify){phin[util.promisify.custom]=phin.promisified}module.exports=phin;
- }).call(this,require("buffer").Buffer)
- },{"buffer":47,"http":335,"https":252,"querystring":316,"url":359,"util":365,"zlib":34}],288:[function(require,module,exports){
- 'use strict';
- module.exports = pixelmatch;
- function pixelmatch(img1, img2, output, width, height, options) {
- if (!options) options = {};
- var threshold = options.threshold === undefined ? 0.1 : options.threshold;
- // maximum acceptable square distance between two colors;
- // 35215 is the maximum possible value for the YIQ difference metric
- var maxDelta = 35215 * threshold * threshold,
- diff = 0;
- // compare each pixel of one image against the other one
- for (var y = 0; y < height; y++) {
- for (var x = 0; x < width; x++) {
- var pos = (y * width + x) * 4;
- // squared YUV distance between colors at this pixel position
- var delta = colorDelta(img1, img2, pos, pos);
- // the color difference is above the threshold
- if (delta > maxDelta) {
- // check it's a real rendering difference or just anti-aliasing
- if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) ||
- antialiased(img2, x, y, width, height, img1))) {
- // one of the pixels is anti-aliasing; draw as yellow and do not count as difference
- if (output) drawPixel(output, pos, 255, 255, 0);
- } else {
- // found substantial difference not caused by anti-aliasing; draw it as red
- if (output) drawPixel(output, pos, 255, 0, 0);
- diff++;
- }
- } else if (output) {
- // pixels are similar; draw background as grayscale image blended with white
- var val = blend(grayPixel(img1, pos), 0.1);
- drawPixel(output, pos, val, val, val);
- }
- }
- }
- // return the number of different pixels
- return diff;
- }
- // check if a pixel is likely a part of anti-aliasing;
- // based on "Anti-aliased Pixel and Intensity Slope Detector" paper by V. Vysniauskas, 2009
- function antialiased(img, x1, y1, width, height, img2) {
- var x0 = Math.max(x1 - 1, 0),
- y0 = Math.max(y1 - 1, 0),
- x2 = Math.min(x1 + 1, width - 1),
- y2 = Math.min(y1 + 1, height - 1),
- pos = (y1 * width + x1) * 4,
- zeroes = 0,
- positives = 0,
- negatives = 0,
- min = 0,
- max = 0,
- minX, minY, maxX, maxY;
- // go through 8 adjacent pixels
- for (var x = x0; x <= x2; x++) {
- for (var y = y0; y <= y2; y++) {
- if (x === x1 && y === y1) continue;
- // brightness delta between the center pixel and adjacent one
- var delta = colorDelta(img, img, pos, (y * width + x) * 4, true);
- // count the number of equal, darker and brighter adjacent pixels
- if (delta === 0) zeroes++;
- else if (delta < 0) negatives++;
- else if (delta > 0) positives++;
- // if found more than 2 equal siblings, it's definitely not anti-aliasing
- if (zeroes > 2) return false;
- if (!img2) continue;
- // remember the darkest pixel
- if (delta < min) {
- min = delta;
- minX = x;
- minY = y;
- }
- // remember the brightest pixel
- if (delta > max) {
- max = delta;
- maxX = x;
- maxY = y;
- }
- }
- }
- if (!img2) return true;
- // if there are no both darker and brighter pixels among siblings, it's not anti-aliasing
- if (negatives === 0 || positives === 0) return false;
- // if either the darkest or the brightest pixel has more than 2 equal siblings in both images
- // (definitely not anti-aliased), this pixel is anti-aliased
- return (!antialiased(img, minX, minY, width, height) && !antialiased(img2, minX, minY, width, height)) ||
- (!antialiased(img, maxX, maxY, width, height) && !antialiased(img2, maxX, maxY, width, height));
- }
- // calculate color difference according to the paper "Measuring perceived color difference
- // using YIQ NTSC transmission color space in mobile applications" by Y. Kotsarenko and F. Ramos
- function colorDelta(img1, img2, k, m, yOnly) {
- var a1 = img1[k + 3] / 255,
- a2 = img2[m + 3] / 255,
- r1 = blend(img1[k + 0], a1),
- g1 = blend(img1[k + 1], a1),
- b1 = blend(img1[k + 2], a1),
- r2 = blend(img2[m + 0], a2),
- g2 = blend(img2[m + 1], a2),
- b2 = blend(img2[m + 2], a2),
- y = rgb2y(r1, g1, b1) - rgb2y(r2, g2, b2);
- if (yOnly) return y; // brightness difference only
- var i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2),
- q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2);
- return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;
- }
- function rgb2y(r, g, b) { return r * 0.29889531 + g * 0.58662247 + b * 0.11448223; }
- function rgb2i(r, g, b) { return r * 0.59597799 - g * 0.27417610 - b * 0.32180189; }
- function rgb2q(r, g, b) { return r * 0.21147017 - g * 0.52261711 + b * 0.31114694; }
- // blend semi-transparent color with white
- function blend(c, a) {
- return 255 + (c - 255) * a;
- }
- function drawPixel(output, pos, r, g, b) {
- output[pos + 0] = r;
- output[pos + 1] = g;
- output[pos + 2] = b;
- output[pos + 3] = 255;
- }
- function grayPixel(img, i) {
- var a = img[i + 3] / 255,
- r = blend(img[i + 0], a),
- g = blend(img[i + 1], a),
- b = blend(img[i + 2], a);
- return rgb2y(r, g, b);
- }
- },{}],289:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var interlaceUtils = require('./interlace');
- var pixelBppMap = {
- 1: { // L
- 0: 0,
- 1: 0,
- 2: 0,
- 3: 0xff
- },
- 2: { // LA
- 0: 0,
- 1: 0,
- 2: 0,
- 3: 1
- },
- 3: { // RGB
- 0: 0,
- 1: 1,
- 2: 2,
- 3: 0xff
- },
- 4: { // RGBA
- 0: 0,
- 1: 1,
- 2: 2,
- 3: 3
- }
- };
- function bitRetriever(data, depth) {
- var leftOver = [];
- var i = 0;
- function split() {
- if (i === data.length) {
- throw new Error('Ran out of data');
- }
- var byte = data[i];
- i++;
- var byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
- switch (depth) {
- default:
- throw new Error('unrecognised depth');
- case 16:
- byte2 = data[i];
- i++;
- leftOver.push(((byte << 8) + byte2));
- break;
- case 4:
- byte2 = byte & 0x0f;
- byte1 = byte >> 4;
- leftOver.push(byte1, byte2);
- break;
- case 2:
- byte4 = byte & 3;
- byte3 = byte >> 2 & 3;
- byte2 = byte >> 4 & 3;
- byte1 = byte >> 6 & 3;
- leftOver.push(byte1, byte2, byte3, byte4);
- break;
- case 1:
- byte8 = byte & 1;
- byte7 = byte >> 1 & 1;
- byte6 = byte >> 2 & 1;
- byte5 = byte >> 3 & 1;
- byte4 = byte >> 4 & 1;
- byte3 = byte >> 5 & 1;
- byte2 = byte >> 6 & 1;
- byte1 = byte >> 7 & 1;
- leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
- break;
- }
- }
- return {
- get: function(count) {
- while (leftOver.length < count) {
- split();
- }
- var returner = leftOver.slice(0, count);
- leftOver = leftOver.slice(count);
- return returner;
- },
- resetAfterLine: function() {
- leftOver.length = 0;
- },
- end: function() {
- if (i !== data.length) {
- throw new Error('extra data found');
- }
- }
- };
- }
- function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { // eslint-disable-line max-params
- var imageWidth = image.width;
- var imageHeight = image.height;
- var imagePass = image.index;
- for (var y = 0; y < imageHeight; y++) {
- for (var x = 0; x < imageWidth; x++) {
- var pxPos = getPxPos(x, y, imagePass);
- for (var i = 0; i < 4; i++) {
- var idx = pixelBppMap[bpp][i];
- if (idx === 0xff) {
- pxData[pxPos + i] = 0xff;
- } else {
- var dataPos = idx + rawPos;
- if (dataPos === data.length) {
- throw new Error('Ran out of data');
- }
- pxData[pxPos + i] = data[dataPos];
- }
- }
- rawPos += bpp; //eslint-disable-line no-param-reassign
- }
- }
- return rawPos;
- }
- function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { // eslint-disable-line max-params
- var imageWidth = image.width;
- var imageHeight = image.height;
- var imagePass = image.index;
- for (var y = 0; y < imageHeight; y++) {
- for (var x = 0; x < imageWidth; x++) {
- var pixelData = bits.get(bpp);
- var pxPos = getPxPos(x, y, imagePass);
- for (var i = 0; i < 4; i++) {
- var idx = pixelBppMap[bpp][i];
- pxData[pxPos + i] = idx !== 0xff ? pixelData[idx] : maxBit;
- }
- }
- bits.resetAfterLine();
- }
- }
- exports.dataToBitMap = function(data, bitmapInfo) {
- var width = bitmapInfo.width;
- var height = bitmapInfo.height;
- var depth = bitmapInfo.depth;
- var bpp = bitmapInfo.bpp;
- var interlace = bitmapInfo.interlace;
- if (depth !== 8) {
- var bits = bitRetriever(data, depth);
- }
- var pxData;
- if (depth <= 8) {
- pxData = new Buffer(width * height * 4);
- }
- else {
- pxData = new Uint16Array(width * height * 4);
- }
- var maxBit = Math.pow(2, depth) - 1;
- var rawPos = 0;
- var images;
- var getPxPos;
- if (interlace) {
- images = interlaceUtils.getImagePasses(width, height);
- getPxPos = interlaceUtils.getInterlaceIterator(width, height);
- }
- else {
- var nonInterlacedPxPos = 0;
- getPxPos = function() {
- var returner = nonInterlacedPxPos;
- nonInterlacedPxPos += 4;
- return returner;
- };
- images = [{ width: width, height: height }];
- }
- for (var imageIndex = 0; imageIndex < images.length; imageIndex++) {
- if (depth === 8) {
- rawPos = mapImage8Bit(images[imageIndex], pxData, getPxPos, bpp, data, rawPos);
- }
- else {
- mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit);
- }
- }
- if (depth === 8) {
- if (rawPos !== data.length) {
- throw new Error('extra data found');
- }
- }
- else {
- bits.end();
- }
- return pxData;
- };
- }).call(this,require("buffer").Buffer)
- },{"./interlace":299,"buffer":47}],290:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var constants = require('./constants');
- module.exports = function(dataIn, width, height, options) {
- var outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(options.colorType) !== -1;
- if (options.colorType === options.inputColorType) {
- var bigEndian = (function() {
- var buffer = new ArrayBuffer(2);
- new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
- // Int16Array uses the platform's endianness.
- return new Int16Array(buffer)[0] !== 256;
- })();
- // If no need to convert to grayscale and alpha is present/absent in both, take a fast route
- if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)){
- return dataIn;
- }
- }
- // map to a UInt16 array if data is 16bit, fix endianness below
- var data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
- var maxValue = 255;
- var inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
- if (inBpp == 4 && !options.inputHasAlpha) inBpp = 3;
- var outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
- if (options.bitDepth === 16) {
- maxValue = 65535;
- outBpp *= 2;
- }
- var outData = new Buffer(width * height * outBpp);
- var inIndex = 0;
- var outIndex = 0;
- var bgColor = options.bgColor || {};
- if (bgColor.red === undefined) {
- bgColor.red = maxValue;
- }
- if (bgColor.green === undefined) {
- bgColor.green = maxValue;
- }
- if (bgColor.blue === undefined) {
- bgColor.blue = maxValue;
- }
- function getRGBA(data, inIndex) {
- var red, green, blue, alpha = maxValue;
- switch (options.inputColorType) {
- case constants.COLORTYPE_COLOR_ALPHA:
- alpha = data[inIndex + 3];
- red = data[inIndex];
- green = data[inIndex+1];
- blue = data[inIndex+2];
- break;
- case constants.COLORTYPE_COLOR:
- red = data[inIndex];
- green = data[inIndex+1];
- blue = data[inIndex+2];
- break;
- case constants.COLORTYPE_ALPHA:
- alpha = data[inIndex + 1];
- red = data[inIndex];
- green = red;
- blue = red;
- break;
- case constants.COLORTYPE_GRAYSCALE:
- red = data[inIndex];
- green = red;
- blue = red;
- break;
- default:
- throw new Error('input color type:' + options.inputColorType + ' is not supported at present');
- }
- if (options.inputHasAlpha) {
- if (!outHasAlpha) {
- alpha /= maxValue;
- red = Math.min(Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), maxValue);
- green = Math.min(Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), maxValue);
- blue = Math.min(Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), maxValue);
- }
- }
- return {red: red, green: green, blue: blue, alpha: alpha};
- }
- for (var y = 0; y < height; y++) {
- for (var x = 0; x < width; x++) {
- var rgba = getRGBA(data, inIndex);
- switch (options.colorType) {
- case constants.COLORTYPE_COLOR_ALPHA:
- case constants.COLORTYPE_COLOR:
- if (options.bitDepth === 8) {
- outData[outIndex] = rgba.red;
- outData[outIndex + 1] = rgba.green;
- outData[outIndex + 2] = rgba.blue;
- if (outHasAlpha) {
- outData[outIndex + 3] = rgba.alpha;
- }
- } else {
- outData.writeUInt16BE(rgba.red, outIndex);
- outData.writeUInt16BE(rgba.green, outIndex + 2);
- outData.writeUInt16BE(rgba.blue, outIndex + 4);
- if (outHasAlpha) {
- outData.writeUInt16BE(rgba.alpha, outIndex + 6);
- }
- }
- break;
- case constants.COLORTYPE_ALPHA:
- case constants.COLORTYPE_GRAYSCALE:
- // Convert to grayscale and alpha
- var grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
- if (options.bitDepth === 8) {
- outData[outIndex] = grayscale;
- if (outHasAlpha) {
- outData[outIndex + 1] = rgba.alpha;
- }
- } else {
- outData.writeUInt16BE(grayscale, outIndex);
- if (outHasAlpha) {
- outData.writeUInt16BE(rgba.alpha, outIndex + 2);
- }
- }
- break;
- }
- inIndex += inBpp;
- outIndex += outBpp;
- }
- }
- return outData;
- };
- }).call(this,require("buffer").Buffer)
- },{"./constants":292,"buffer":47}],291:[function(require,module,exports){
- (function (process,Buffer){
- 'use strict';
- var util = require('util');
- var Stream = require('stream');
- var ChunkStream = module.exports = function() {
- Stream.call(this);
- this._buffers = [];
- this._buffered = 0;
- this._reads = [];
- this._paused = false;
- this._encoding = 'utf8';
- this.writable = true;
- };
- util.inherits(ChunkStream, Stream);
- ChunkStream.prototype.read = function(length, callback) {
- this._reads.push({
- length: Math.abs(length), // if length < 0 then at most this length
- allowLess: length < 0,
- func: callback
- });
- process.nextTick(function() {
- this._process();
- // its paused and there is not enought data then ask for more
- if (this._paused && this._reads.length > 0) {
- this._paused = false;
- this.emit('drain');
- }
- }.bind(this));
- };
- ChunkStream.prototype.write = function(data, encoding) {
- if (!this.writable) {
- this.emit('error', new Error('Stream not writable'));
- return false;
- }
- var dataBuffer;
- if (Buffer.isBuffer(data)) {
- dataBuffer = data;
- }
- else {
- dataBuffer = new Buffer(data, encoding || this._encoding);
- }
- this._buffers.push(dataBuffer);
- this._buffered += dataBuffer.length;
- this._process();
- // ok if there are no more read requests
- if (this._reads && this._reads.length === 0) {
- this._paused = true;
- }
- return this.writable && !this._paused;
- };
- ChunkStream.prototype.end = function(data, encoding) {
- if (data) {
- this.write(data, encoding);
- }
- this.writable = false;
- // already destroyed
- if (!this._buffers) {
- return;
- }
- // enqueue or handle end
- if (this._buffers.length === 0) {
- this._end();
- }
- else {
- this._buffers.push(null);
- this._process();
- }
- };
- ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
- ChunkStream.prototype._end = function() {
- if (this._reads.length > 0) {
- this.emit('error',
- new Error('There are some read requests waiting on finished stream')
- );
- }
- this.destroy();
- };
- ChunkStream.prototype.destroy = function() {
- if (!this._buffers) {
- return;
- }
- this.writable = false;
- this._reads = null;
- this._buffers = null;
- this.emit('close');
- };
- ChunkStream.prototype._processReadAllowingLess = function(read) {
- // ok there is any data so that we can satisfy this request
- this._reads.shift(); // == read
- // first we need to peek into first buffer
- var smallerBuf = this._buffers[0];
- // ok there is more data than we need
- if (smallerBuf.length > read.length) {
- this._buffered -= read.length;
- this._buffers[0] = smallerBuf.slice(read.length);
- read.func.call(this, smallerBuf.slice(0, read.length));
- }
- else {
- // ok this is less than maximum length so use it all
- this._buffered -= smallerBuf.length;
- this._buffers.shift(); // == smallerBuf
- read.func.call(this, smallerBuf);
- }
- };
- ChunkStream.prototype._processRead = function(read) {
- this._reads.shift(); // == read
- var pos = 0;
- var count = 0;
- var data = new Buffer(read.length);
- // create buffer for all data
- while (pos < read.length) {
- var buf = this._buffers[count++];
- var len = Math.min(buf.length, read.length - pos);
- buf.copy(data, pos, 0, len);
- pos += len;
- // last buffer wasn't used all so just slice it and leave
- if (len !== buf.length) {
- this._buffers[--count] = buf.slice(len);
- }
- }
- // remove all used buffers
- if (count > 0) {
- this._buffers.splice(0, count);
- }
- this._buffered -= read.length;
- read.func.call(this, data);
- };
- ChunkStream.prototype._process = function() {
- try {
- // as long as there is any data and read requests
- while (this._buffered > 0 && this._reads && this._reads.length > 0) {
- var read = this._reads[0];
- // read any data (but no more than length)
- if (read.allowLess) {
- this._processReadAllowingLess(read);
- }
- else if (this._buffered >= read.length) {
- // ok we can meet some expectations
- this._processRead(read);
- }
- else {
- // not enought data to satisfy first request in queue
- // so we need to wait for more
- break;
- }
- }
- if (this._buffers && this._buffers.length > 0 && this._buffers[0] === null) {
- this._end();
- }
- }
- catch (ex) {
- this.emit('error', ex);
- }
- };
- }).call(this,require('_process'),require("buffer").Buffer)
- },{"_process":312,"buffer":47,"stream":334,"util":365}],292:[function(require,module,exports){
- 'use strict';
- module.exports = {
- PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
- TYPE_IHDR: 0x49484452,
- TYPE_IEND: 0x49454e44,
- TYPE_IDAT: 0x49444154,
- TYPE_PLTE: 0x504c5445,
- TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
- TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
- // color-type bits
- COLORTYPE_GRAYSCALE: 0,
- COLORTYPE_PALETTE: 1,
- COLORTYPE_COLOR: 2,
- COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
- // color-type combinations
- COLORTYPE_PALETTE_COLOR: 3,
- COLORTYPE_COLOR_ALPHA: 6,
- COLORTYPE_TO_BPP_MAP: {
- 0: 1,
- 2: 3,
- 3: 1,
- 4: 2,
- 6: 4
- },
- GAMMA_DIVISION: 100000
- };
- },{}],293:[function(require,module,exports){
- 'use strict';
- var crcTable = [];
- (function() {
- for (var i = 0; i < 256; i++) {
- var currentCrc = i;
- for (var j = 0; j < 8; j++) {
- if (currentCrc & 1) {
- currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
- }
- else {
- currentCrc = currentCrc >>> 1;
- }
- }
- crcTable[i] = currentCrc;
- }
- }());
- var CrcCalculator = module.exports = function() {
- this._crc = -1;
- };
- CrcCalculator.prototype.write = function(data) {
- for (var i = 0; i < data.length; i++) {
- this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
- }
- return true;
- };
- CrcCalculator.prototype.crc32 = function() {
- return this._crc ^ -1;
- };
- CrcCalculator.crc32 = function(buf) {
- var crc = -1;
- for (var i = 0; i < buf.length; i++) {
- crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
- }
- return crc ^ -1;
- };
- },{}],294:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var paethPredictor = require('./paeth-predictor');
- function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
- for (var x = 0; x < byteWidth; x++) {
- rawData[rawPos + x] = pxData[pxPos + x];
- }
- }
- function filterSumNone(pxData, pxPos, byteWidth) {
- var sum = 0;
- var length = pxPos + byteWidth;
- for (var i = pxPos; i < length; i++) {
- sum += Math.abs(pxData[i]);
- }
- return sum;
- }
- function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
- for (var x = 0; x < byteWidth; x++) {
- var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
- var val = pxData[pxPos + x] - left;
- rawData[rawPos + x] = val;
- }
- }
- function filterSumSub(pxData, pxPos, byteWidth, bpp) {
- var sum = 0;
- for (var x = 0; x < byteWidth; x++) {
- var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
- var val = pxData[pxPos + x] - left;
- sum += Math.abs(val);
- }
- return sum;
- }
- function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
- for (var x = 0; x < byteWidth; x++) {
- var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
- var val = pxData[pxPos + x] - up;
- rawData[rawPos + x] = val;
- }
- }
- function filterSumUp(pxData, pxPos, byteWidth) {
- var sum = 0;
- var length = pxPos + byteWidth;
- for (var x = pxPos; x < length; x++) {
- var up = pxPos > 0 ? pxData[x - byteWidth] : 0;
- var val = pxData[x] - up;
- sum += Math.abs(val);
- }
- return sum;
- }
- function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
- for (var x = 0; x < byteWidth; x++) {
- var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
- var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
- var val = pxData[pxPos + x] - ((left + up) >> 1);
- rawData[rawPos + x] = val;
- }
- }
- function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
- var sum = 0;
- for (var x = 0; x < byteWidth; x++) {
- var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
- var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
- var val = pxData[pxPos + x] - ((left + up) >> 1);
- sum += Math.abs(val);
- }
- return sum;
- }
- function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
- for (var x = 0; x < byteWidth; x++) {
- var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
- var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
- var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
- var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
- rawData[rawPos + x] = val;
- }
- }
- function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
- var sum = 0;
- for (var x = 0; x < byteWidth; x++) {
- var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
- var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
- var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
- var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
- sum += Math.abs(val);
- }
- return sum;
- }
- var filters = {
- 0: filterNone,
- 1: filterSub,
- 2: filterUp,
- 3: filterAvg,
- 4: filterPaeth
- };
- var filterSums = {
- 0: filterSumNone,
- 1: filterSumSub,
- 2: filterSumUp,
- 3: filterSumAvg,
- 4: filterSumPaeth
- };
- module.exports = function(pxData, width, height, options, bpp) {
- var filterTypes;
- if (!('filterType' in options) || options.filterType === -1) {
- filterTypes = [0, 1, 2, 3, 4];
- }
- else if (typeof options.filterType === 'number') {
- filterTypes = [options.filterType];
- }
- else {
- throw new Error('unrecognised filter types');
- }
- if (options.bitDepth === 16) bpp *= 2;
- var byteWidth = width * bpp;
- var rawPos = 0;
- var pxPos = 0;
- var rawData = new Buffer((byteWidth + 1) * height);
- var sel = filterTypes[0];
- for (var y = 0; y < height; y++) {
- if (filterTypes.length > 1) {
- // find best filter for this line (with lowest sum of values)
- var min = Infinity;
- for (var i = 0; i < filterTypes.length; i++) {
- var sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
- if (sum < min) {
- sel = filterTypes[i];
- min = sum;
- }
- }
- }
- rawData[rawPos] = sel;
- rawPos++;
- filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
- rawPos += byteWidth;
- pxPos += byteWidth;
- }
- return rawData;
- };
- }).call(this,require("buffer").Buffer)
- },{"./paeth-predictor":303,"buffer":47}],295:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var util = require('util');
- var ChunkStream = require('./chunkstream');
- var Filter = require('./filter-parse');
- var FilterAsync = module.exports = function(bitmapInfo) {
- ChunkStream.call(this);
- var buffers = [];
- var that = this;
- this._filter = new Filter(bitmapInfo, {
- read: this.read.bind(this),
- write: function(buffer) {
- buffers.push(buffer);
- },
- complete: function() {
- that.emit('complete', Buffer.concat(buffers));
- }
- });
- this._filter.start();
- };
- util.inherits(FilterAsync, ChunkStream);
- }).call(this,require("buffer").Buffer)
- },{"./chunkstream":291,"./filter-parse":297,"buffer":47,"util":365}],296:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var SyncReader = require('./sync-reader');
- var Filter = require('./filter-parse');
- exports.process = function(inBuffer, bitmapInfo) {
- var outBuffers = [];
- var reader = new SyncReader(inBuffer);
- var filter = new Filter(bitmapInfo, {
- read: reader.read.bind(reader),
- write: function(bufferPart) {
- outBuffers.push(bufferPart);
- },
- complete: function() {
- }
- });
- filter.start();
- reader.process();
- return Buffer.concat(outBuffers);
- };
- }).call(this,require("buffer").Buffer)
- },{"./filter-parse":297,"./sync-reader":310,"buffer":47}],297:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var interlaceUtils = require('./interlace');
- var paethPredictor = require('./paeth-predictor');
- function getByteWidth(width, bpp, depth) {
- var byteWidth = width * bpp;
- if (depth !== 8) {
- byteWidth = Math.ceil(byteWidth / (8 / depth));
- }
- return byteWidth;
- }
- var Filter = module.exports = function(bitmapInfo, dependencies) {
- var width = bitmapInfo.width;
- var height = bitmapInfo.height;
- var interlace = bitmapInfo.interlace;
- var bpp = bitmapInfo.bpp;
- var depth = bitmapInfo.depth;
- this.read = dependencies.read;
- this.write = dependencies.write;
- this.complete = dependencies.complete;
- this._imageIndex = 0;
- this._images = [];
- if (interlace) {
- var passes = interlaceUtils.getImagePasses(width, height);
- for (var i = 0; i < passes.length; i++) {
- this._images.push({
- byteWidth: getByteWidth(passes[i].width, bpp, depth),
- height: passes[i].height,
- lineIndex: 0
- });
- }
- }
- else {
- this._images.push({
- byteWidth: getByteWidth(width, bpp, depth),
- height: height,
- lineIndex: 0
- });
- }
- // when filtering the line we look at the pixel to the left
- // the spec also says it is done on a byte level regardless of the number of pixels
- // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back
- // a pixel rather than just a different byte part. However if we are sub byte, we ignore.
- if (depth === 8) {
- this._xComparison = bpp;
- }
- else if (depth === 16) {
- this._xComparison = bpp * 2;
- }
- else {
- this._xComparison = 1;
- }
- };
- Filter.prototype.start = function() {
- this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this));
- };
- Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
- var xComparison = this._xComparison;
- var xBiggerThan = xComparison - 1;
- for (var x = 0; x < byteWidth; x++) {
- var rawByte = rawData[1 + x];
- var f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
- unfilteredLine[x] = rawByte + f1Left;
- }
- };
- Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
- var lastLine = this._lastLine;
- for (var x = 0; x < byteWidth; x++) {
- var rawByte = rawData[1 + x];
- var f2Up = lastLine ? lastLine[x] : 0;
- unfilteredLine[x] = rawByte + f2Up;
- }
- };
- Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
- var xComparison = this._xComparison;
- var xBiggerThan = xComparison - 1;
- var lastLine = this._lastLine;
- for (var x = 0; x < byteWidth; x++) {
- var rawByte = rawData[1 + x];
- var f3Up = lastLine ? lastLine[x] : 0;
- var f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
- var f3Add = Math.floor((f3Left + f3Up) / 2);
- unfilteredLine[x] = rawByte + f3Add;
- }
- };
- Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
- var xComparison = this._xComparison;
- var xBiggerThan = xComparison - 1;
- var lastLine = this._lastLine;
- for (var x = 0; x < byteWidth; x++) {
- var rawByte = rawData[1 + x];
- var f4Up = lastLine ? lastLine[x] : 0;
- var f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
- var f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
- var f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
- unfilteredLine[x] = rawByte + f4Add;
- }
- };
- Filter.prototype._reverseFilterLine = function(rawData) {
- var filter = rawData[0];
- var unfilteredLine;
- var currentImage = this._images[this._imageIndex];
- var byteWidth = currentImage.byteWidth;
- if (filter === 0) {
- unfilteredLine = rawData.slice(1, byteWidth + 1);
- }
- else {
- unfilteredLine = new Buffer(byteWidth);
- switch (filter) {
- case 1:
- this._unFilterType1(rawData, unfilteredLine, byteWidth);
- break;
- case 2:
- this._unFilterType2(rawData, unfilteredLine, byteWidth);
- break;
- case 3:
- this._unFilterType3(rawData, unfilteredLine, byteWidth);
- break;
- case 4:
- this._unFilterType4(rawData, unfilteredLine, byteWidth);
- break;
- default:
- throw new Error('Unrecognised filter type - ' + filter);
- }
- }
- this.write(unfilteredLine);
- currentImage.lineIndex++;
- if (currentImage.lineIndex >= currentImage.height) {
- this._lastLine = null;
- this._imageIndex++;
- currentImage = this._images[this._imageIndex];
- }
- else {
- this._lastLine = unfilteredLine;
- }
- if (currentImage) {
- // read, using the byte width that may be from the new current image
- this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
- }
- else {
- this._lastLine = null;
- this.complete();
- }
- };
- }).call(this,require("buffer").Buffer)
- },{"./interlace":299,"./paeth-predictor":303,"buffer":47}],298:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- function dePalette(indata, outdata, width, height, palette) {
- var pxPos = 0;
- // use values from palette
- for (var y = 0; y < height; y++) {
- for (var x = 0; x < width; x++) {
- var color = palette[indata[pxPos]];
- if (!color) {
- throw new Error('index ' + indata[pxPos] + ' not in palette');
- }
- for (var i = 0; i < 4; i++) {
- outdata[pxPos + i] = color[i];
- }
- pxPos += 4;
- }
- }
- }
- function replaceTransparentColor(indata, outdata, width, height, transColor) {
- var pxPos = 0;
- for (var y = 0; y < height; y++) {
- for (var x = 0; x < width; x++) {
- var makeTrans = false;
- if (transColor.length === 1) {
- if (transColor[0] === indata[pxPos]) {
- makeTrans = true;
- }
- }
- else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
- makeTrans = true;
- }
- if (makeTrans) {
- for (var i = 0; i < 4; i++) {
- outdata[pxPos + i] = 0;
- }
- }
- pxPos += 4;
- }
- }
- }
- function scaleDepth(indata, outdata, width, height, depth) {
- var maxOutSample = 255;
- var maxInSample = Math.pow(2, depth) - 1;
- var pxPos = 0;
- for (var y = 0; y < height; y++) {
- for (var x = 0; x < width; x++) {
- for (var i = 0; i < 4; i++) {
- outdata[pxPos + i] = Math.floor((indata[pxPos + i] * maxOutSample) / maxInSample + 0.5);
- }
- pxPos += 4;
- }
- }
- }
- module.exports = function(indata, imageData) {
- var depth = imageData.depth;
- var width = imageData.width;
- var height = imageData.height;
- var colorType = imageData.colorType;
- var transColor = imageData.transColor;
- var palette = imageData.palette;
- var outdata = indata; // only different for 16 bits
- if (colorType === 3) { // paletted
- dePalette(indata, outdata, width, height, palette);
- }
- else {
- if (transColor) {
- replaceTransparentColor(indata, outdata, width, height, transColor);
- }
- // if it needs scaling
- if (depth !== 8) {
- // if we need to change the buffer size
- if (depth === 16) {
- outdata = new Buffer(width * height * 4);
- }
- scaleDepth(indata, outdata, width, height, depth);
- }
- }
- return outdata;
- };
- }).call(this,require("buffer").Buffer)
- },{"buffer":47}],299:[function(require,module,exports){
- 'use strict';
- // Adam 7
- // 0 1 2 3 4 5 6 7
- // 0 x 6 4 6 x 6 4 6
- // 1 7 7 7 7 7 7 7 7
- // 2 5 6 5 6 5 6 5 6
- // 3 7 7 7 7 7 7 7 7
- // 4 3 6 4 6 3 6 4 6
- // 5 7 7 7 7 7 7 7 7
- // 6 5 6 5 6 5 6 5 6
- // 7 7 7 7 7 7 7 7 7
- var imagePasses = [
- { // pass 1 - 1px
- x: [0],
- y: [0]
- },
- { // pass 2 - 1px
- x: [4],
- y: [0]
- },
- { // pass 3 - 2px
- x: [0, 4],
- y: [4]
- },
- { // pass 4 - 4px
- x: [2, 6],
- y: [0, 4]
- },
- { // pass 5 - 8px
- x: [0, 2, 4, 6],
- y: [2, 6]
- },
- { // pass 6 - 16px
- x: [1, 3, 5, 7],
- y: [0, 2, 4, 6]
- },
- { // pass 7 - 32px
- x: [0, 1, 2, 3, 4, 5, 6, 7],
- y: [1, 3, 5, 7]
- }
- ];
- exports.getImagePasses = function(width, height) {
- var images = [];
- var xLeftOver = width % 8;
- var yLeftOver = height % 8;
- var xRepeats = (width - xLeftOver) / 8;
- var yRepeats = (height - yLeftOver) / 8;
- for (var i = 0; i < imagePasses.length; i++) {
- var pass = imagePasses[i];
- var passWidth = xRepeats * pass.x.length;
- var passHeight = yRepeats * pass.y.length;
- for (var j = 0; j < pass.x.length; j++) {
- if (pass.x[j] < xLeftOver) {
- passWidth++;
- }
- else {
- break;
- }
- }
- for (j = 0; j < pass.y.length; j++) {
- if (pass.y[j] < yLeftOver) {
- passHeight++;
- }
- else {
- break;
- }
- }
- if (passWidth > 0 && passHeight > 0) {
- images.push({ width: passWidth, height: passHeight, index: i });
- }
- }
- return images;
- };
- exports.getInterlaceIterator = function(width) {
- return function(x, y, pass) {
- var outerXLeftOver = x % imagePasses[pass].x.length;
- var outerX = (((x - outerXLeftOver) / imagePasses[pass].x.length) * 8) + imagePasses[pass].x[outerXLeftOver];
- var outerYLeftOver = y % imagePasses[pass].y.length;
- var outerY = (((y - outerYLeftOver) / imagePasses[pass].y.length) * 8) + imagePasses[pass].y[outerYLeftOver];
- return (outerX * 4) + (outerY * width * 4);
- };
- };
- },{}],300:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var util = require('util');
- var Stream = require('stream');
- var constants = require('./constants');
- var Packer = require('./packer');
- var PackerAsync = module.exports = function(opt) {
- Stream.call(this);
- var options = opt || {};
- this._packer = new Packer(options);
- this._deflate = this._packer.createDeflate();
- this.readable = true;
- };
- util.inherits(PackerAsync, Stream);
- PackerAsync.prototype.pack = function(data, width, height, gamma) {
- // Signature
- this.emit('data', new Buffer(constants.PNG_SIGNATURE));
- this.emit('data', this._packer.packIHDR(width, height));
- if (gamma) {
- this.emit('data', this._packer.packGAMA(gamma));
- }
- var filteredData = this._packer.filterData(data, width, height);
- // compress it
- this._deflate.on('error', this.emit.bind(this, 'error'));
- this._deflate.on('data', function(compressedData) {
- this.emit('data', this._packer.packIDAT(compressedData));
- }.bind(this));
- this._deflate.on('end', function() {
- this.emit('data', this._packer.packIEND());
- this.emit('end');
- }.bind(this));
- this._deflate.end(filteredData);
- };
- }).call(this,require("buffer").Buffer)
- },{"./constants":292,"./packer":302,"buffer":47,"stream":334,"util":365}],301:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var hasSyncZlib = true;
- var zlib = require('zlib');
- if (!zlib.deflateSync) {
- hasSyncZlib = false;
- }
- var constants = require('./constants');
- var Packer = require('./packer');
- module.exports = function(metaData, opt) {
- if (!hasSyncZlib) {
- throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
- }
- var options = opt || {};
- var packer = new Packer(options);
- var chunks = [];
- // Signature
- chunks.push(new Buffer(constants.PNG_SIGNATURE));
- // Header
- chunks.push(packer.packIHDR(metaData.width, metaData.height));
- if (metaData.gamma) {
- chunks.push(packer.packGAMA(metaData.gamma));
- }
- var filteredData = packer.filterData(metaData.data, metaData.width, metaData.height);
- // compress it
- var compressedData = zlib.deflateSync(filteredData, packer.getDeflateOptions());
- filteredData = null;
- if (!compressedData || !compressedData.length) {
- throw new Error('bad png - invalid compressed data response');
- }
- chunks.push(packer.packIDAT(compressedData));
- // End
- chunks.push(packer.packIEND());
- return Buffer.concat(chunks);
- };
- }).call(this,require("buffer").Buffer)
- },{"./constants":292,"./packer":302,"buffer":47,"zlib":34}],302:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var constants = require('./constants');
- var CrcStream = require('./crc');
- var bitPacker = require('./bitpacker');
- var filter = require('./filter-pack');
- var zlib = require('zlib');
- var Packer = module.exports = function(options) {
- this._options = options;
- options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
- options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9;
- options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3;
- options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
- options.deflateFactory = options.deflateFactory || zlib.createDeflate;
- options.bitDepth = options.bitDepth || 8;
- // This is outputColorType
- options.colorType = (typeof options.colorType === 'number') ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
- options.inputColorType = (typeof options.inputColorType === 'number') ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
- if ([
- constants.COLORTYPE_GRAYSCALE,
- constants.COLORTYPE_COLOR,
- constants.COLORTYPE_COLOR_ALPHA,
- constants.COLORTYPE_ALPHA
- ].indexOf(options.colorType) === -1) {
- throw new Error('option color type:' + options.colorType + ' is not supported at present');
- }
- if ([
- constants.COLORTYPE_GRAYSCALE,
- constants.COLORTYPE_COLOR,
- constants.COLORTYPE_COLOR_ALPHA,
- constants.COLORTYPE_ALPHA
- ].indexOf(options.inputColorType) === -1) {
- throw new Error('option input color type:' + options.inputColorType + ' is not supported at present');
- }
- if (options.bitDepth !== 8 && options.bitDepth !== 16) {
- throw new Error('option bit depth:' + options.bitDepth + ' is not supported at present');
- }
- };
- Packer.prototype.getDeflateOptions = function() {
- return {
- chunkSize: this._options.deflateChunkSize,
- level: this._options.deflateLevel,
- strategy: this._options.deflateStrategy
- };
- };
- Packer.prototype.createDeflate = function() {
- return this._options.deflateFactory(this.getDeflateOptions());
- };
- Packer.prototype.filterData = function(data, width, height) {
- // convert to correct format for filtering (e.g. right bpp and bit depth)
- var packedData = bitPacker(data, width, height, this._options);
- // filter pixel data
- var bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
- var filteredData = filter(packedData, width, height, this._options, bpp);
- return filteredData;
- };
- Packer.prototype._packChunk = function(type, data) {
- var len = (data ? data.length : 0);
- var buf = new Buffer(len + 12);
- buf.writeUInt32BE(len, 0);
- buf.writeUInt32BE(type, 4);
- if (data) {
- data.copy(buf, 8);
- }
- buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
- return buf;
- };
- Packer.prototype.packGAMA = function(gamma) {
- var buf = new Buffer(4);
- buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
- return this._packChunk(constants.TYPE_gAMA, buf);
- };
- Packer.prototype.packIHDR = function(width, height) {
- var buf = new Buffer(13);
- buf.writeUInt32BE(width, 0);
- buf.writeUInt32BE(height, 4);
- buf[8] = this._options.bitDepth; // Bit depth
- buf[9] = this._options.colorType; // colorType
- buf[10] = 0; // compression
- buf[11] = 0; // filter
- buf[12] = 0; // interlace
- return this._packChunk(constants.TYPE_IHDR, buf);
- };
- Packer.prototype.packIDAT = function(data) {
- return this._packChunk(constants.TYPE_IDAT, data);
- };
- Packer.prototype.packIEND = function() {
- return this._packChunk(constants.TYPE_IEND, null);
- };
- }).call(this,require("buffer").Buffer)
- },{"./bitpacker":290,"./constants":292,"./crc":293,"./filter-pack":294,"buffer":47,"zlib":34}],303:[function(require,module,exports){
- 'use strict';
- module.exports = function paethPredictor(left, above, upLeft) {
- var paeth = left + above - upLeft;
- var pLeft = Math.abs(paeth - left);
- var pAbove = Math.abs(paeth - above);
- var pUpLeft = Math.abs(paeth - upLeft);
- if (pLeft <= pAbove && pLeft <= pUpLeft) {
- return left;
- }
- if (pAbove <= pUpLeft) {
- return above;
- }
- return upLeft;
- };
- },{}],304:[function(require,module,exports){
- 'use strict';
- var util = require('util');
- var zlib = require('zlib');
- var ChunkStream = require('./chunkstream');
- var FilterAsync = require('./filter-parse-async');
- var Parser = require('./parser');
- var bitmapper = require('./bitmapper');
- var formatNormaliser = require('./format-normaliser');
- var ParserAsync = module.exports = function(options) {
- ChunkStream.call(this);
- this._parser = new Parser(options, {
- read: this.read.bind(this),
- error: this._handleError.bind(this),
- metadata: this._handleMetaData.bind(this),
- gamma: this.emit.bind(this, 'gamma'),
- palette: this._handlePalette.bind(this),
- transColor: this._handleTransColor.bind(this),
- finished: this._finished.bind(this),
- inflateData: this._inflateData.bind(this)
- });
- this._options = options;
- this.writable = true;
- this._parser.start();
- };
- util.inherits(ParserAsync, ChunkStream);
- ParserAsync.prototype._handleError = function(err) {
- this.emit('error', err);
- this.writable = false;
- this.destroy();
- if (this._inflate && this._inflate.destroy) {
- this._inflate.destroy();
- }
- if (this._filter) {
- this._filter.destroy();
- // For backward compatibility with Node 7 and below.
- // Suppress errors due to _inflate calling write() even after
- // it's destroy()'ed.
- this._filter.on('error', function() {});
- }
- this.errord = true;
- };
- ParserAsync.prototype._inflateData = function(data) {
- if (!this._inflate) {
- if (this._bitmapInfo.interlace) {
- this._inflate = zlib.createInflate();
- this._inflate.on('error', this.emit.bind(this, 'error'));
- this._filter.on('complete', this._complete.bind(this));
- this._inflate.pipe(this._filter);
- } else {
- var rowSize = ((this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7) >> 3) + 1;
- var imageSize = rowSize * this._bitmapInfo.height;
- var chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
-
- this._inflate = zlib.createInflate({ chunkSize: chunkSize });
- var leftToInflate = imageSize;
- var emitError = this.emit.bind(this, 'error');
- this._inflate.on('error', function(err) {
- if (!leftToInflate) {
- return;
- }
- emitError(err);
- });
- this._filter.on('complete', this._complete.bind(this));
- var filterWrite = this._filter.write.bind(this._filter);
- this._inflate.on('data', function(chunk) {
- if (!leftToInflate) {
- return;
- }
- if (chunk.length > leftToInflate) {
- chunk = chunk.slice(0, leftToInflate);
- }
- leftToInflate -= chunk.length;
- filterWrite(chunk);
- });
- this._inflate.on('end', this._filter.end.bind(this._filter));
- }
- }
- this._inflate.write(data);
- };
- ParserAsync.prototype._handleMetaData = function(metaData) {
- this.emit('metadata', metaData);
- this._bitmapInfo = Object.create(metaData);
- this._filter = new FilterAsync(this._bitmapInfo);
- };
- ParserAsync.prototype._handleTransColor = function(transColor) {
- this._bitmapInfo.transColor = transColor;
- };
- ParserAsync.prototype._handlePalette = function(palette) {
- this._bitmapInfo.palette = palette;
- };
- ParserAsync.prototype._finished = function() {
- if (this.errord) {
- return;
- }
- if (!this._inflate) {
- this.emit('error', 'No Inflate block');
- }
- else {
- // no more data to inflate
- this._inflate.end();
- }
- this.destroySoon();
- };
- ParserAsync.prototype._complete = function(filteredData) {
- if (this.errord) {
- return;
- }
- try {
- var bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
- var normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo);
- bitmapData = null;
- }
- catch (ex) {
- this._handleError(ex);
- return;
- }
- this.emit('parsed', normalisedBitmapData);
- };
- },{"./bitmapper":289,"./chunkstream":291,"./filter-parse-async":295,"./format-normaliser":298,"./parser":306,"util":365,"zlib":34}],305:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var hasSyncZlib = true;
- var zlib = require('zlib');
- var inflateSync = require('./sync-inflate');
- if (!zlib.deflateSync) {
- hasSyncZlib = false;
- }
- var SyncReader = require('./sync-reader');
- var FilterSync = require('./filter-parse-sync');
- var Parser = require('./parser');
- var bitmapper = require('./bitmapper');
- var formatNormaliser = require('./format-normaliser');
- module.exports = function(buffer, options) {
- if (!hasSyncZlib) {
- throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
- }
- var err;
- function handleError(_err_) {
- err = _err_;
- }
- var metaData;
- function handleMetaData(_metaData_) {
- metaData = _metaData_;
- }
- function handleTransColor(transColor) {
- metaData.transColor = transColor;
- }
- function handlePalette(palette) {
- metaData.palette = palette;
- }
- var gamma;
- function handleGamma(_gamma_) {
- gamma = _gamma_;
- }
- var inflateDataList = [];
- function handleInflateData(inflatedData) {
- inflateDataList.push(inflatedData);
- }
- var reader = new SyncReader(buffer);
- var parser = new Parser(options, {
- read: reader.read.bind(reader),
- error: handleError,
- metadata: handleMetaData,
- gamma: handleGamma,
- palette: handlePalette,
- transColor: handleTransColor,
- inflateData: handleInflateData
- });
- parser.start();
- reader.process();
- if (err) {
- throw err;
- }
- //join together the inflate datas
- var inflateData = Buffer.concat(inflateDataList);
- inflateDataList.length = 0;
- var inflatedData;
- if (metaData.interlace) {
- inflatedData = zlib.inflateSync(inflateData);
- } else {
- var rowSize = ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;
- var imageSize = rowSize * metaData.height;
- inflatedData = inflateSync(inflateData, { chunkSize: imageSize, maxLength: imageSize });
- }
- inflateData = null;
- if (!inflatedData || !inflatedData.length) {
- throw new Error('bad png - invalid inflate data response');
- }
- var unfilteredData = FilterSync.process(inflatedData, metaData);
- inflateData = null;
- var bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
- unfilteredData = null;
- var normalisedBitmapData = formatNormaliser(bitmapData, metaData);
- metaData.data = normalisedBitmapData;
- metaData.gamma = gamma || 0;
- return metaData;
- };
- }).call(this,require("buffer").Buffer)
- },{"./bitmapper":289,"./filter-parse-sync":296,"./format-normaliser":298,"./parser":306,"./sync-inflate":309,"./sync-reader":310,"buffer":47,"zlib":34}],306:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var constants = require('./constants');
- var CrcCalculator = require('./crc');
- var Parser = module.exports = function(options, dependencies) {
- this._options = options;
- options.checkCRC = options.checkCRC !== false;
- this._hasIHDR = false;
- this._hasIEND = false;
- // input flags/metadata
- this._palette = [];
- this._colorType = 0;
- this._chunks = {};
- this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
- this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
- this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
- this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
- this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
- this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
- this.read = dependencies.read;
- this.error = dependencies.error;
- this.metadata = dependencies.metadata;
- this.gamma = dependencies.gamma;
- this.transColor = dependencies.transColor;
- this.palette = dependencies.palette;
- this.parsed = dependencies.parsed;
- this.inflateData = dependencies.inflateData;
- this.finished = dependencies.finished;
- };
- Parser.prototype.start = function() {
- this.read(constants.PNG_SIGNATURE.length,
- this._parseSignature.bind(this)
- );
- };
- Parser.prototype._parseSignature = function(data) {
- var signature = constants.PNG_SIGNATURE;
- for (var i = 0; i < signature.length; i++) {
- if (data[i] !== signature[i]) {
- this.error(new Error('Invalid file signature'));
- return;
- }
- }
- this.read(8, this._parseChunkBegin.bind(this));
- };
- Parser.prototype._parseChunkBegin = function(data) {
- // chunk content length
- var length = data.readUInt32BE(0);
- // chunk type
- var type = data.readUInt32BE(4);
- var name = '';
- for (var i = 4; i < 8; i++) {
- name += String.fromCharCode(data[i]);
- }
- //console.log('chunk ', name, length);
- // chunk flags
- var ancillary = Boolean(data[4] & 0x20); // or critical
- // priv = Boolean(data[5] & 0x20), // or public
- // safeToCopy = Boolean(data[7] & 0x20); // or unsafe
- if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
- this.error(new Error('Expected IHDR on beggining'));
- return;
- }
- this._crc = new CrcCalculator();
- this._crc.write(new Buffer(name));
- if (this._chunks[type]) {
- return this._chunks[type](length);
- }
- if (!ancillary) {
- this.error(new Error('Unsupported critical chunk type ' + name));
- return;
- }
- this.read(length + 4, this._skipChunk.bind(this));
- };
- Parser.prototype._skipChunk = function(/*data*/) {
- this.read(8, this._parseChunkBegin.bind(this));
- };
- Parser.prototype._handleChunkEnd = function() {
- this.read(4, this._parseChunkEnd.bind(this));
- };
- Parser.prototype._parseChunkEnd = function(data) {
- var fileCrc = data.readInt32BE(0);
- var calcCrc = this._crc.crc32();
- // check CRC
- if (this._options.checkCRC && calcCrc !== fileCrc) {
- this.error(new Error('Crc error - ' + fileCrc + ' - ' + calcCrc));
- return;
- }
- if (!this._hasIEND) {
- this.read(8, this._parseChunkBegin.bind(this));
- }
- };
- Parser.prototype._handleIHDR = function(length) {
- this.read(length, this._parseIHDR.bind(this));
- };
- Parser.prototype._parseIHDR = function(data) {
- this._crc.write(data);
- var width = data.readUInt32BE(0);
- var height = data.readUInt32BE(4);
- var depth = data[8];
- var colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
- var compr = data[10];
- var filter = data[11];
- var interlace = data[12];
- // console.log(' width', width, 'height', height,
- // 'depth', depth, 'colorType', colorType,
- // 'compr', compr, 'filter', filter, 'interlace', interlace
- // );
- if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
- this.error(new Error('Unsupported bit depth ' + depth));
- return;
- }
- if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
- this.error(new Error('Unsupported color type'));
- return;
- }
- if (compr !== 0) {
- this.error(new Error('Unsupported compression method'));
- return;
- }
- if (filter !== 0) {
- this.error(new Error('Unsupported filter method'));
- return;
- }
- if (interlace !== 0 && interlace !== 1) {
- this.error(new Error('Unsupported interlace method'));
- return;
- }
- this._colorType = colorType;
- var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
- this._hasIHDR = true;
- this.metadata({
- width: width,
- height: height,
- depth: depth,
- interlace: Boolean(interlace),
- palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
- color: Boolean(colorType & constants.COLORTYPE_COLOR),
- alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
- bpp: bpp,
- colorType: colorType
- });
- this._handleChunkEnd();
- };
- Parser.prototype._handlePLTE = function(length) {
- this.read(length, this._parsePLTE.bind(this));
- };
- Parser.prototype._parsePLTE = function(data) {
- this._crc.write(data);
- var entries = Math.floor(data.length / 3);
- // console.log('Palette:', entries);
- for (var i = 0; i < entries; i++) {
- this._palette.push([
- data[i * 3],
- data[i * 3 + 1],
- data[i * 3 + 2],
- 0xff
- ]);
- }
- this.palette(this._palette);
- this._handleChunkEnd();
- };
- Parser.prototype._handleTRNS = function(length) {
- this.read(length, this._parseTRNS.bind(this));
- };
- Parser.prototype._parseTRNS = function(data) {
- this._crc.write(data);
- // palette
- if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
- if (this._palette.length === 0) {
- this.error(new Error('Transparency chunk must be after palette'));
- return;
- }
- if (data.length > this._palette.length) {
- this.error(new Error('More transparent colors than palette size'));
- return;
- }
- for (var i = 0; i < data.length; i++) {
- this._palette[i][3] = data[i];
- }
- this.palette(this._palette);
- }
- // for colorType 0 (grayscale) and 2 (rgb)
- // there might be one gray/color defined as transparent
- if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
- // grey, 2 bytes
- this.transColor([data.readUInt16BE(0)]);
- }
- if (this._colorType === constants.COLORTYPE_COLOR) {
- this.transColor([data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4)]);
- }
- this._handleChunkEnd();
- };
- Parser.prototype._handleGAMA = function(length) {
- this.read(length, this._parseGAMA.bind(this));
- };
- Parser.prototype._parseGAMA = function(data) {
- this._crc.write(data);
- this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
- this._handleChunkEnd();
- };
- Parser.prototype._handleIDAT = function(length) {
- this.read(-length, this._parseIDAT.bind(this, length));
- };
- Parser.prototype._parseIDAT = function(length, data) {
- this._crc.write(data);
- if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
- throw new Error('Expected palette not found');
- }
- this.inflateData(data);
- var leftOverLength = length - data.length;
- if (leftOverLength > 0) {
- this._handleIDAT(leftOverLength);
- }
- else {
- this._handleChunkEnd();
- }
- };
- Parser.prototype._handleIEND = function(length) {
- this.read(length, this._parseIEND.bind(this));
- };
- Parser.prototype._parseIEND = function(data) {
- this._crc.write(data);
- this._hasIEND = true;
- this._handleChunkEnd();
- if (this.finished) {
- this.finished();
- }
- };
- }).call(this,require("buffer").Buffer)
- },{"./constants":292,"./crc":293,"buffer":47}],307:[function(require,module,exports){
- 'use strict';
- var parse = require('./parser-sync');
- var pack = require('./packer-sync');
- exports.read = function(buffer, options) {
- return parse(buffer, options || {});
- };
- exports.write = function(png, options) {
- return pack(png, options);
- };
- },{"./packer-sync":301,"./parser-sync":305}],308:[function(require,module,exports){
- (function (process,Buffer){
- 'use strict';
- var util = require('util');
- var Stream = require('stream');
- var Parser = require('./parser-async');
- var Packer = require('./packer-async');
- var PNGSync = require('./png-sync');
- var PNG = exports.PNG = function(options) {
- Stream.call(this);
- options = options || {}; // eslint-disable-line no-param-reassign
- // coerce pixel dimensions to integers (also coerces undefined -> 0):
- this.width = options.width | 0;
- this.height = options.height | 0;
- this.data = this.width > 0 && this.height > 0 ?
- new Buffer(4 * this.width * this.height) : null;
- if (options.fill && this.data) {
- this.data.fill(0);
- }
- this.gamma = 0;
- this.readable = this.writable = true;
- this._parser = new Parser(options);
- this._parser.on('error', this.emit.bind(this, 'error'));
- this._parser.on('close', this._handleClose.bind(this));
- this._parser.on('metadata', this._metadata.bind(this));
- this._parser.on('gamma', this._gamma.bind(this));
- this._parser.on('parsed', function(data) {
- this.data = data;
- this.emit('parsed', data);
- }.bind(this));
- this._packer = new Packer(options);
- this._packer.on('data', this.emit.bind(this, 'data'));
- this._packer.on('end', this.emit.bind(this, 'end'));
- this._parser.on('close', this._handleClose.bind(this));
- this._packer.on('error', this.emit.bind(this, 'error'));
- };
- util.inherits(PNG, Stream);
- PNG.sync = PNGSync;
- PNG.prototype.pack = function() {
- if (!this.data || !this.data.length) {
- this.emit('error', 'No data provided');
- return this;
- }
- process.nextTick(function() {
- this._packer.pack(this.data, this.width, this.height, this.gamma);
- }.bind(this));
- return this;
- };
- PNG.prototype.parse = function(data, callback) {
- if (callback) {
- var onParsed, onError;
- onParsed = function(parsedData) {
- this.removeListener('error', onError);
- this.data = parsedData;
- callback(null, this);
- }.bind(this);
- onError = function(err) {
- this.removeListener('parsed', onParsed);
- callback(err, null);
- }.bind(this);
- this.once('parsed', onParsed);
- this.once('error', onError);
- }
- this.end(data);
- return this;
- };
- PNG.prototype.write = function(data) {
- this._parser.write(data);
- return true;
- };
- PNG.prototype.end = function(data) {
- this._parser.end(data);
- };
- PNG.prototype._metadata = function(metadata) {
- this.width = metadata.width;
- this.height = metadata.height;
- this.emit('metadata', metadata);
- };
- PNG.prototype._gamma = function(gamma) {
- this.gamma = gamma;
- };
- PNG.prototype._handleClose = function() {
- if (!this._parser.writable && !this._packer.readable) {
- this.emit('close');
- }
- };
- PNG.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
- // coerce pixel dimensions to integers (also coerces undefined -> 0):
- /* eslint-disable no-param-reassign */
- srcX |= 0;
- srcY |= 0;
- width |= 0;
- height |= 0;
- deltaX |= 0;
- deltaY |= 0;
- /* eslint-enable no-param-reassign */
- if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
- throw new Error('bitblt reading outside image');
- }
- if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
- throw new Error('bitblt writing outside image');
- }
- for (var y = 0; y < height; y++) {
- src.data.copy(dst.data,
- ((deltaY + y) * dst.width + deltaX) << 2,
- ((srcY + y) * src.width + srcX) << 2,
- ((srcY + y) * src.width + srcX + width) << 2
- );
- }
- };
- PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
- PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
- return this;
- };
- PNG.adjustGamma = function(src) {
- if (src.gamma) {
- for (var y = 0; y < src.height; y++) {
- for (var x = 0; x < src.width; x++) {
- var idx = (src.width * y + x) << 2;
- for (var i = 0; i < 3; i++) {
- var sample = src.data[idx + i] / 255;
- sample = Math.pow(sample, 1 / 2.2 / src.gamma);
- src.data[idx + i] = Math.round(sample * 255);
- }
- }
- }
- src.gamma = 0;
- }
- };
- PNG.prototype.adjustGamma = function() {
- PNG.adjustGamma(this);
- };
- }).call(this,require('_process'),require("buffer").Buffer)
- },{"./packer-async":300,"./parser-async":304,"./png-sync":307,"_process":312,"buffer":47,"stream":334,"util":365}],309:[function(require,module,exports){
- (function (process,Buffer){
- 'use strict';
- var assert = require('assert').ok;
- var zlib = require('zlib');
- var util = require('util');
- var kMaxLength = require('buffer').kMaxLength;
- function Inflate(opts) {
- if (!(this instanceof Inflate)) {
- return new Inflate(opts);
- }
- if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
- opts.chunkSize = zlib.Z_MIN_CHUNK;
- }
- zlib.Inflate.call(this, opts);
- // Node 8 --> 9 compatibility check
- this._offset = this._offset === undefined ? this._outOffset : this._offset;
- this._buffer = this._buffer || this._outBuffer;
- if (opts && opts.maxLength != null) {
- this._maxLength = opts.maxLength;
- }
- }
- function createInflate(opts) {
- return new Inflate(opts);
- }
- function _close(engine, callback) {
- if (callback) {
- process.nextTick(callback);
- }
- // Caller may invoke .close after a zlib error (which will null _handle).
- if (!engine._handle) {
- return;
- }
- engine._handle.close();
- engine._handle = null;
- }
- Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
- if (typeof asyncCb === 'function') {
- return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
- }
- var self = this;
- var availInBefore = chunk && chunk.length;
- var availOutBefore = this._chunkSize - this._offset;
- var leftToInflate = this._maxLength;
- var inOff = 0;
- var buffers = [];
- var nread = 0;
- var error;
- this.on('error', function(err) {
- error = err;
- });
- function handleChunk(availInAfter, availOutAfter) {
- if (self._hadError) {
- return;
- }
- var have = availOutBefore - availOutAfter;
- assert(have >= 0, 'have should not go down');
- if (have > 0) {
- var out = self._buffer.slice(self._offset, self._offset + have);
- self._offset += have;
- if (out.length > leftToInflate) {
- out = out.slice(0, leftToInflate);
- }
- buffers.push(out);
- nread += out.length;
- leftToInflate -= out.length;
- if (leftToInflate === 0) {
- return false;
- }
- }
- if (availOutAfter === 0 || self._offset >= self._chunkSize) {
- availOutBefore = self._chunkSize;
- self._offset = 0;
- self._buffer = Buffer.allocUnsafe(self._chunkSize);
- }
- if (availOutAfter === 0) {
- inOff += (availInBefore - availInAfter);
- availInBefore = availInAfter;
- return true;
- }
- return false;
- }
- assert(this._handle, 'zlib binding closed');
- do {
- var res = this._handle.writeSync(flushFlag,
- chunk, // in
- inOff, // in_off
- availInBefore, // in_len
- this._buffer, // out
- this._offset, //out_off
- availOutBefore); // out_len
- // Node 8 --> 9 compatibility check
- res = res || this._writeState;
- } while (!this._hadError && handleChunk(res[0], res[1]));
- if (this._hadError) {
- throw error;
- }
- if (nread >= kMaxLength) {
- _close(this);
- throw new RangeError('Cannot create final Buffer. It would be larger than 0x' + kMaxLength.toString(16) + ' bytes');
- }
- var buf = Buffer.concat(buffers, nread);
- _close(this);
- return buf;
- };
- util.inherits(Inflate, zlib.Inflate);
- function zlibBufferSync(engine, buffer) {
- if (typeof buffer === 'string') {
- buffer = Buffer.from(buffer);
- }
- if (!(buffer instanceof Buffer)) {
- throw new TypeError('Not a string or buffer');
- }
- var flushFlag = engine._finishFlushFlag;
- if (flushFlag == null) {
- flushFlag = zlib.Z_FINISH;
- }
- return engine._processChunk(buffer, flushFlag);
- }
- function inflateSync(buffer, opts) {
- return zlibBufferSync(new Inflate(opts), buffer);
- }
- module.exports = exports = inflateSync;
- exports.Inflate = Inflate;
- exports.createInflate = createInflate;
- exports.inflateSync = inflateSync;
- }).call(this,require('_process'),require("buffer").Buffer)
- },{"_process":312,"assert":24,"buffer":47,"util":365,"zlib":34}],310:[function(require,module,exports){
- 'use strict';
- var SyncReader = module.exports = function(buffer) {
- this._buffer = buffer;
- this._reads = [];
- };
- SyncReader.prototype.read = function(length, callback) {
- this._reads.push({
- length: Math.abs(length), // if length < 0 then at most this length
- allowLess: length < 0,
- func: callback
- });
- };
- SyncReader.prototype.process = function() {
- // as long as there is any data and read requests
- while (this._reads.length > 0 && this._buffer.length) {
- var read = this._reads[0];
- if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
- // ok there is any data so that we can satisfy this request
- this._reads.shift(); // == read
- var buf = this._buffer;
- this._buffer = buf.slice(read.length);
- read.func.call(this, buf.slice(0, read.length));
- }
- else {
- break;
- }
- }
- if (this._reads.length > 0) {
- return new Error('There are some read requests waitng on finished stream');
- }
- if (this._buffer.length > 0) {
- return new Error('unrecognised content at end of stream');
- }
- };
- },{}],311:[function(require,module,exports){
- (function (process){
- 'use strict';
- if (typeof process === 'undefined' ||
- !process.version ||
- process.version.indexOf('v0.') === 0 ||
- process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
- module.exports = { nextTick: nextTick };
- } else {
- module.exports = process
- }
- function nextTick(fn, arg1, arg2, arg3) {
- if (typeof fn !== 'function') {
- throw new TypeError('"callback" argument must be a function');
- }
- var len = arguments.length;
- var args, i;
- switch (len) {
- case 0:
- case 1:
- return process.nextTick(fn);
- case 2:
- return process.nextTick(function afterTickOne() {
- fn.call(null, arg1);
- });
- case 3:
- return process.nextTick(function afterTickTwo() {
- fn.call(null, arg1, arg2);
- });
- case 4:
- return process.nextTick(function afterTickThree() {
- fn.call(null, arg1, arg2, arg3);
- });
- default:
- args = new Array(len - 1);
- i = 0;
- while (i < args.length) {
- args[i++] = arguments[i];
- }
- return process.nextTick(function afterTick() {
- fn.apply(null, args);
- });
- }
- }
- }).call(this,require('_process'))
- },{"_process":312}],312:[function(require,module,exports){
- // shim for using process in browser
- var process = module.exports = {};
- // cached from whatever global is present so that test runners that stub it
- // don't break things. But we need to wrap it in a try catch in case it is
- // wrapped in strict mode code which doesn't define any globals. It's inside a
- // function because try/catches deoptimize in certain engines.
- var cachedSetTimeout;
- var cachedClearTimeout;
- function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
- }
- function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
- }
- (function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
- } ())
- function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // 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
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
- }
- function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // 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.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
- }
- var queue = [];
- var draining = false;
- var currentQueue;
- var queueIndex = -1;
- function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
- }
- function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
- }
- process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
- };
- // v8 likes predictible objects
- function Item(fun, array) {
- this.fun = fun;
- this.array = array;
- }
- Item.prototype.run = function () {
- this.fun.apply(null, this.array);
- };
- process.title = 'browser';
- process.browser = true;
- process.env = {};
- process.argv = [];
- process.version = ''; // empty string to avoid regexp issues
- process.versions = {};
- function noop() {}
- process.on = noop;
- process.addListener = noop;
- process.once = noop;
- process.off = noop;
- process.removeListener = noop;
- process.removeAllListeners = noop;
- process.emit = noop;
- process.prependListener = noop;
- process.prependOnceListener = noop;
- process.listeners = function (name) { return [] }
- process.binding = function (name) {
- throw new Error('process.binding is not supported');
- };
- process.cwd = function () { return '/' };
- process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
- };
- process.umask = function() { return 0; };
- },{}],313:[function(require,module,exports){
- (function (global){
- /*! https://mths.be/punycode v1.4.1 by @mathias */
- ;(function(root) {
- /** Detect free variables */
- var freeExports = typeof exports == 'object' && exports &&
- !exports.nodeType && exports;
- var freeModule = typeof module == 'object' && module &&
- !module.nodeType && module;
- var freeGlobal = typeof global == 'object' && global;
- if (
- freeGlobal.global === freeGlobal ||
- freeGlobal.window === freeGlobal ||
- freeGlobal.self === freeGlobal
- ) {
- root = freeGlobal;
- }
- /**
- * The `punycode` object.
- * @name punycode
- * @type Object
- */
- var punycode,
- /** Highest positive signed 32-bit float value */
- maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
- /** Bootstring parameters */
- base = 36,
- tMin = 1,
- tMax = 26,
- skew = 38,
- damp = 700,
- initialBias = 72,
- initialN = 128, // 0x80
- delimiter = '-', // '\x2D'
- /** Regular expressions */
- regexPunycode = /^xn--/,
- regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
- regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
- /** Error messages */
- errors = {
- 'overflow': 'Overflow: input needs wider integers to process',
- 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
- 'invalid-input': 'Invalid input'
- },
- /** Convenience shortcuts */
- baseMinusTMin = base - tMin,
- floor = Math.floor,
- stringFromCharCode = String.fromCharCode,
- /** Temporary variable */
- key;
- /*--------------------------------------------------------------------------*/
- /**
- * A generic error utility function.
- * @private
- * @param {String} type The error type.
- * @returns {Error} Throws a `RangeError` with the applicable error message.
- */
- function error(type) {
- throw new RangeError(errors[type]);
- }
- /**
- * A generic `Array#map` utility function.
- * @private
- * @param {Array} array The array to iterate over.
- * @param {Function} callback The function that gets called for every array
- * item.
- * @returns {Array} A new array of values returned by the callback function.
- */
- function map(array, fn) {
- var length = array.length;
- var result = [];
- while (length--) {
- result[length] = fn(array[length]);
- }
- return result;
- }
- /**
- * A simple `Array#map`-like wrapper to work with domain name strings or email
- * addresses.
- * @private
- * @param {String} domain The domain name or email address.
- * @param {Function} callback The function that gets called for every
- * character.
- * @returns {Array} A new string of characters returned by the callback
- * function.
- */
- function mapDomain(string, fn) {
- var parts = string.split('@');
- var result = '';
- if (parts.length > 1) {
- // In email addresses, only the domain name should be punycoded. Leave
- // the local part (i.e. everything up to `@`) intact.
- result = parts[0] + '@';
- string = parts[1];
- }
- // Avoid `split(regex)` for IE8 compatibility. See #17.
- string = string.replace(regexSeparators, '\x2E');
- var labels = string.split('.');
- var encoded = map(labels, fn).join('.');
- return result + encoded;
- }
- /**
- * Creates an array containing the numeric code points of each Unicode
- * character in the string. While JavaScript uses UCS-2 internally,
- * this function will convert a pair of surrogate halves (each of which
- * UCS-2 exposes as separate characters) into a single code point,
- * matching UTF-16.
- * @see `punycode.ucs2.encode`
- * @see <https://mathiasbynens.be/notes/javascript-encoding>
- * @memberOf punycode.ucs2
- * @name decode
- * @param {String} string The Unicode input string (UCS-2).
- * @returns {Array} The new array of code points.
- */
- function ucs2decode(string) {
- var output = [],
- counter = 0,
- length = string.length,
- value,
- extra;
- while (counter < length) {
- value = string.charCodeAt(counter++);
- if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
- // high surrogate, and there is a next character
- extra = string.charCodeAt(counter++);
- if ((extra & 0xFC00) == 0xDC00) { // low surrogate
- output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
- } else {
- // unmatched surrogate; only append this code unit, in case the next
- // code unit is the high surrogate of a surrogate pair
- output.push(value);
- counter--;
- }
- } else {
- output.push(value);
- }
- }
- return output;
- }
- /**
- * Creates a string based on an array of numeric code points.
- * @see `punycode.ucs2.decode`
- * @memberOf punycode.ucs2
- * @name encode
- * @param {Array} codePoints The array of numeric code points.
- * @returns {String} The new Unicode string (UCS-2).
- */
- function ucs2encode(array) {
- return map(array, function(value) {
- var output = '';
- if (value > 0xFFFF) {
- value -= 0x10000;
- output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
- value = 0xDC00 | value & 0x3FF;
- }
- output += stringFromCharCode(value);
- return output;
- }).join('');
- }
- /**
- * Converts a basic code point into a digit/integer.
- * @see `digitToBasic()`
- * @private
- * @param {Number} codePoint The basic numeric code point value.
- * @returns {Number} The numeric value of a basic code point (for use in
- * representing integers) in the range `0` to `base - 1`, or `base` if
- * the code point does not represent a value.
- */
- function basicToDigit(codePoint) {
- if (codePoint - 48 < 10) {
- return codePoint - 22;
- }
- if (codePoint - 65 < 26) {
- return codePoint - 65;
- }
- if (codePoint - 97 < 26) {
- return codePoint - 97;
- }
- return base;
- }
- /**
- * Converts a digit/integer into a basic code point.
- * @see `basicToDigit()`
- * @private
- * @param {Number} digit The numeric value of a basic code point.
- * @returns {Number} The basic code point whose value (when used for
- * representing integers) is `digit`, which needs to be in the range
- * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
- * used; else, the lowercase form is used. The behavior is undefined
- * if `flag` is non-zero and `digit` has no uppercase form.
- */
- function digitToBasic(digit, flag) {
- // 0..25 map to ASCII a..z or A..Z
- // 26..35 map to ASCII 0..9
- return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
- }
- /**
- * Bias adaptation function as per section 3.4 of RFC 3492.
- * https://tools.ietf.org/html/rfc3492#section-3.4
- * @private
- */
- function adapt(delta, numPoints, firstTime) {
- var k = 0;
- delta = firstTime ? floor(delta / damp) : delta >> 1;
- delta += floor(delta / numPoints);
- for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
- delta = floor(delta / baseMinusTMin);
- }
- return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
- }
- /**
- * Converts a Punycode string of ASCII-only symbols to a string of Unicode
- * symbols.
- * @memberOf punycode
- * @param {String} input The Punycode string of ASCII-only symbols.
- * @returns {String} The resulting string of Unicode symbols.
- */
- function decode(input) {
- // Don't use UCS-2
- var output = [],
- inputLength = input.length,
- out,
- i = 0,
- n = initialN,
- bias = initialBias,
- basic,
- j,
- index,
- oldi,
- w,
- k,
- digit,
- t,
- /** Cached calculation results */
- baseMinusT;
- // Handle the basic code points: let `basic` be the number of input code
- // points before the last delimiter, or `0` if there is none, then copy
- // the first basic code points to the output.
- basic = input.lastIndexOf(delimiter);
- if (basic < 0) {
- basic = 0;
- }
- for (j = 0; j < basic; ++j) {
- // if it's not a basic code point
- if (input.charCodeAt(j) >= 0x80) {
- error('not-basic');
- }
- output.push(input.charCodeAt(j));
- }
- // Main decoding loop: start just after the last delimiter if any basic code
- // points were copied; start at the beginning otherwise.
- for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
- // `index` is the index of the next character to be consumed.
- // Decode a generalized variable-length integer into `delta`,
- // which gets added to `i`. The overflow checking is easier
- // if we increase `i` as we go, then subtract off its starting
- // value at the end to obtain `delta`.
- for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
- if (index >= inputLength) {
- error('invalid-input');
- }
- digit = basicToDigit(input.charCodeAt(index++));
- if (digit >= base || digit > floor((maxInt - i) / w)) {
- error('overflow');
- }
- i += digit * w;
- t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
- if (digit < t) {
- break;
- }
- baseMinusT = base - t;
- if (w > floor(maxInt / baseMinusT)) {
- error('overflow');
- }
- w *= baseMinusT;
- }
- out = output.length + 1;
- bias = adapt(i - oldi, out, oldi == 0);
- // `i` was supposed to wrap around from `out` to `0`,
- // incrementing `n` each time, so we'll fix that now:
- if (floor(i / out) > maxInt - n) {
- error('overflow');
- }
- n += floor(i / out);
- i %= out;
- // Insert `n` at position `i` of the output
- output.splice(i++, 0, n);
- }
- return ucs2encode(output);
- }
- /**
- * Converts a string of Unicode symbols (e.g. a domain name label) to a
- * Punycode string of ASCII-only symbols.
- * @memberOf punycode
- * @param {String} input The string of Unicode symbols.
- * @returns {String} The resulting Punycode string of ASCII-only symbols.
- */
- function encode(input) {
- var n,
- delta,
- handledCPCount,
- basicLength,
- bias,
- j,
- m,
- q,
- k,
- t,
- currentValue,
- output = [],
- /** `inputLength` will hold the number of code points in `input`. */
- inputLength,
- /** Cached calculation results */
- handledCPCountPlusOne,
- baseMinusT,
- qMinusT;
- // Convert the input in UCS-2 to Unicode
- input = ucs2decode(input);
- // Cache the length
- inputLength = input.length;
- // Initialize the state
- n = initialN;
- delta = 0;
- bias = initialBias;
- // Handle the basic code points
- for (j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue < 0x80) {
- output.push(stringFromCharCode(currentValue));
- }
- }
- handledCPCount = basicLength = output.length;
- // `handledCPCount` is the number of code points that have been handled;
- // `basicLength` is the number of basic code points.
- // Finish the basic string - if it is not empty - with a delimiter
- if (basicLength) {
- output.push(delimiter);
- }
- // Main encoding loop:
- while (handledCPCount < inputLength) {
- // All non-basic code points < n have been handled already. Find the next
- // larger one:
- for (m = maxInt, j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue >= n && currentValue < m) {
- m = currentValue;
- }
- }
- // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
- // but guard against overflow
- handledCPCountPlusOne = handledCPCount + 1;
- if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
- error('overflow');
- }
- delta += (m - n) * handledCPCountPlusOne;
- n = m;
- for (j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue < n && ++delta > maxInt) {
- error('overflow');
- }
- if (currentValue == n) {
- // Represent delta as a generalized variable-length integer
- for (q = delta, k = base; /* no condition */; k += base) {
- t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
- if (q < t) {
- break;
- }
- qMinusT = q - t;
- baseMinusT = base - t;
- output.push(
- stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
- );
- q = floor(qMinusT / baseMinusT);
- }
- output.push(stringFromCharCode(digitToBasic(q, 0)));
- bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
- delta = 0;
- ++handledCPCount;
- }
- }
- ++delta;
- ++n;
- }
- return output.join('');
- }
- /**
- * Converts a Punycode string representing a domain name or an email address
- * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
- * it doesn't matter if you call it on a string that has already been
- * converted to Unicode.
- * @memberOf punycode
- * @param {String} input The Punycoded domain name or email address to
- * convert to Unicode.
- * @returns {String} The Unicode representation of the given Punycode
- * string.
- */
- function toUnicode(input) {
- return mapDomain(input, function(string) {
- return regexPunycode.test(string)
- ? decode(string.slice(4).toLowerCase())
- : string;
- });
- }
- /**
- * Converts a Unicode string representing a domain name or an email address to
- * Punycode. Only the non-ASCII parts of the domain name will be converted,
- * i.e. it doesn't matter if you call it with a domain that's already in
- * ASCII.
- * @memberOf punycode
- * @param {String} input The domain name or email address to convert, as a
- * Unicode string.
- * @returns {String} The Punycode representation of the given domain name or
- * email address.
- */
- function toASCII(input) {
- return mapDomain(input, function(string) {
- return regexNonASCII.test(string)
- ? 'xn--' + encode(string)
- : string;
- });
- }
- /*--------------------------------------------------------------------------*/
- /** Define the public API */
- punycode = {
- /**
- * A string representing the current Punycode.js version number.
- * @memberOf punycode
- * @type String
- */
- 'version': '1.4.1',
- /**
- * An object of methods to convert from JavaScript's internal character
- * representation (UCS-2) to Unicode code points, and back.
- * @see <https://mathiasbynens.be/notes/javascript-encoding>
- * @memberOf punycode
- * @type Object
- */
- 'ucs2': {
- 'decode': ucs2decode,
- 'encode': ucs2encode
- },
- 'decode': decode,
- 'encode': encode,
- 'toASCII': toASCII,
- 'toUnicode': toUnicode
- };
- /** Expose `punycode` */
- // Some AMD build optimizers, like r.js, check for specific condition patterns
- // like the following:
- if (
- typeof define == 'function' &&
- typeof define.amd == 'object' &&
- define.amd
- ) {
- define('punycode', function() {
- return punycode;
- });
- } else if (freeExports && freeModule) {
- if (module.exports == freeExports) {
- // in Node.js, io.js, or RingoJS v0.8.0+
- freeModule.exports = punycode;
- } else {
- // in Narwhal or RingoJS v0.7.0-
- for (key in punycode) {
- punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
- }
- }
- } else {
- // in Rhino or a web browser
- root.punycode = punycode;
- }
- }(this));
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],314:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- 'use strict';
- // If obj.hasOwnProperty has been overridden, then calling
- // obj.hasOwnProperty(prop) will break.
- // See: https://github.com/joyent/node/issues/1707
- function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
- module.exports = function(qs, sep, eq, options) {
- sep = sep || '&';
- eq = eq || '=';
- var obj = {};
- if (typeof qs !== 'string' || qs.length === 0) {
- return obj;
- }
- var regexp = /\+/g;
- qs = qs.split(sep);
- var maxKeys = 1000;
- if (options && typeof options.maxKeys === 'number') {
- maxKeys = options.maxKeys;
- }
- var len = qs.length;
- // maxKeys <= 0 means that we should not limit keys count
- if (maxKeys > 0 && len > maxKeys) {
- len = maxKeys;
- }
- for (var i = 0; i < len; ++i) {
- var x = qs[i].replace(regexp, '%20'),
- idx = x.indexOf(eq),
- kstr, vstr, k, v;
- if (idx >= 0) {
- kstr = x.substr(0, idx);
- vstr = x.substr(idx + 1);
- } else {
- kstr = x;
- vstr = '';
- }
- k = decodeURIComponent(kstr);
- v = decodeURIComponent(vstr);
- if (!hasOwnProperty(obj, k)) {
- obj[k] = v;
- } else if (isArray(obj[k])) {
- obj[k].push(v);
- } else {
- obj[k] = [obj[k], v];
- }
- }
- return obj;
- };
- var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
- };
- },{}],315:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- 'use strict';
- var stringifyPrimitive = function(v) {
- switch (typeof v) {
- case 'string':
- return v;
- case 'boolean':
- return v ? 'true' : 'false';
- case 'number':
- return isFinite(v) ? v : '';
- default:
- return '';
- }
- };
- module.exports = function(obj, sep, eq, name) {
- sep = sep || '&';
- eq = eq || '=';
- if (obj === null) {
- obj = undefined;
- }
- if (typeof obj === 'object') {
- return map(objectKeys(obj), function(k) {
- var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
- if (isArray(obj[k])) {
- return map(obj[k], function(v) {
- return ks + encodeURIComponent(stringifyPrimitive(v));
- }).join(sep);
- } else {
- return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
- }
- }).join(sep);
- }
- if (!name) return '';
- return encodeURIComponent(stringifyPrimitive(name)) + eq +
- encodeURIComponent(stringifyPrimitive(obj));
- };
- var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
- };
- function map (xs, f) {
- if (xs.map) return xs.map(f);
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- res.push(f(xs[i], i));
- }
- return res;
- }
- var objectKeys = Object.keys || function (obj) {
- var res = [];
- for (var key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
- }
- return res;
- };
- },{}],316:[function(require,module,exports){
- 'use strict';
- exports.decode = exports.parse = require('./decode');
- exports.encode = exports.stringify = require('./encode');
- },{"./decode":314,"./encode":315}],317:[function(require,module,exports){
- module.exports = require('./lib/_stream_duplex.js');
- },{"./lib/_stream_duplex.js":318}],318:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // a duplex stream is just a stream that is both readable and writable.
- // Since JS doesn't have multiple prototypal inheritance, this class
- // prototypally inherits from Readable, and then parasitically from
- // Writable.
- 'use strict';
- /*<replacement>*/
- var pna = require('process-nextick-args');
- /*</replacement>*/
- /*<replacement>*/
- var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- keys.push(key);
- }return keys;
- };
- /*</replacement>*/
- module.exports = Duplex;
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
- var Readable = require('./_stream_readable');
- var Writable = require('./_stream_writable');
- util.inherits(Duplex, Readable);
- {
- // avoid scope creep, the keys array can then be collected
- var keys = objectKeys(Writable.prototype);
- for (var v = 0; v < keys.length; v++) {
- var method = keys[v];
- if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
- }
- }
- function Duplex(options) {
- if (!(this instanceof Duplex)) return new Duplex(options);
- Readable.call(this, options);
- Writable.call(this, options);
- if (options && options.readable === false) this.readable = false;
- if (options && options.writable === false) this.writable = false;
- this.allowHalfOpen = true;
- if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
- this.once('end', onend);
- }
- Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function () {
- return this._writableState.highWaterMark;
- }
- });
- // the no-half-open enforcer
- function onend() {
- // if we allow half-open state, or if the writable side ended,
- // then we're ok.
- if (this.allowHalfOpen || this._writableState.ended) return;
- // no more data can be written.
- // But allow more writes to happen in this tick.
- pna.nextTick(onEndNT, this);
- }
- function onEndNT(self) {
- self.end();
- }
- Object.defineProperty(Duplex.prototype, 'destroyed', {
- get: function () {
- if (this._readableState === undefined || this._writableState === undefined) {
- return false;
- }
- return this._readableState.destroyed && this._writableState.destroyed;
- },
- set: function (value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (this._readableState === undefined || this._writableState === undefined) {
- return;
- }
- // backward compatibility, the user is explicitly
- // managing destroyed
- this._readableState.destroyed = value;
- this._writableState.destroyed = value;
- }
- });
- Duplex.prototype._destroy = function (err, cb) {
- this.push(null);
- this.end();
- pna.nextTick(cb, err);
- };
- },{"./_stream_readable":320,"./_stream_writable":322,"core-util-is":238,"inherits":254,"process-nextick-args":311}],319:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // a passthrough stream.
- // basically just the most minimal sort of Transform stream.
- // Every written chunk gets output as-is.
- 'use strict';
- module.exports = PassThrough;
- var Transform = require('./_stream_transform');
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
- util.inherits(PassThrough, Transform);
- function PassThrough(options) {
- if (!(this instanceof PassThrough)) return new PassThrough(options);
- Transform.call(this, options);
- }
- PassThrough.prototype._transform = function (chunk, encoding, cb) {
- cb(null, chunk);
- };
- },{"./_stream_transform":321,"core-util-is":238,"inherits":254}],320:[function(require,module,exports){
- (function (process,global){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- 'use strict';
- /*<replacement>*/
- var pna = require('process-nextick-args');
- /*</replacement>*/
- module.exports = Readable;
- /*<replacement>*/
- var isArray = require('isarray');
- /*</replacement>*/
- /*<replacement>*/
- var Duplex;
- /*</replacement>*/
- Readable.ReadableState = ReadableState;
- /*<replacement>*/
- var EE = require('events').EventEmitter;
- var EElistenerCount = function (emitter, type) {
- return emitter.listeners(type).length;
- };
- /*</replacement>*/
- /*<replacement>*/
- var Stream = require('./internal/streams/stream');
- /*</replacement>*/
- /*<replacement>*/
- var Buffer = require('safe-buffer').Buffer;
- var OurUint8Array = global.Uint8Array || function () {};
- function _uint8ArrayToBuffer(chunk) {
- return Buffer.from(chunk);
- }
- function _isUint8Array(obj) {
- return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
- }
- /*</replacement>*/
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
- /*<replacement>*/
- var debugUtil = require('util');
- var debug = void 0;
- if (debugUtil && debugUtil.debuglog) {
- debug = debugUtil.debuglog('stream');
- } else {
- debug = function () {};
- }
- /*</replacement>*/
- var BufferList = require('./internal/streams/BufferList');
- var destroyImpl = require('./internal/streams/destroy');
- var StringDecoder;
- util.inherits(Readable, Stream);
- var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
- function prependListener(emitter, event, fn) {
- // Sadly this is not cacheable as some libraries bundle their own
- // event emitter implementation with them.
- if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
- // This is a hack to make sure that our error handler is attached before any
- // userland ones. NEVER DO THIS. This is here only because this code needs
- // to continue to work with older versions of Node.js that do not include
- // the prependListener() method. The goal is to eventually remove this hack.
- if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
- }
- function ReadableState(options, stream) {
- Duplex = Duplex || require('./_stream_duplex');
- options = options || {};
- // Duplex streams are both readable and writable, but share
- // the same options object.
- // However, some cases require setting options to different
- // values for the readable and the writable sides of the duplex stream.
- // These options can be provided separately as readableXXX and writableXXX.
- var isDuplex = stream instanceof Duplex;
- // object stream flag. Used to make read(n) ignore n and to
- // make all the buffer merging and length checks go away
- this.objectMode = !!options.objectMode;
- if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
- // the point at which it stops calling _read() to fill the buffer
- // Note: 0 is a valid value, means "don't call _read preemptively ever"
- var hwm = options.highWaterMark;
- var readableHwm = options.readableHighWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
- if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
- // cast to ints.
- this.highWaterMark = Math.floor(this.highWaterMark);
- // A linked list is used to store data chunks instead of an array because the
- // linked list can remove elements from the beginning faster than
- // array.shift()
- this.buffer = new BufferList();
- this.length = 0;
- this.pipes = null;
- this.pipesCount = 0;
- this.flowing = null;
- this.ended = false;
- this.endEmitted = false;
- this.reading = false;
- // a flag to be able to tell if the event 'readable'/'data' is emitted
- // immediately, or on a later tick. We set this to true at first, because
- // any actions that shouldn't happen until "later" should generally also
- // not happen before the first read call.
- this.sync = true;
- // whenever we return null, then we set a flag to say
- // that we're awaiting a 'readable' event emission.
- this.needReadable = false;
- this.emittedReadable = false;
- this.readableListening = false;
- this.resumeScheduled = false;
- // has it been destroyed
- this.destroyed = false;
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
- // the number of writers that are awaiting a drain event in .pipe()s
- this.awaitDrain = 0;
- // if true, a maybeReadMore has been scheduled
- this.readingMore = false;
- this.decoder = null;
- this.encoding = null;
- if (options.encoding) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this.decoder = new StringDecoder(options.encoding);
- this.encoding = options.encoding;
- }
- }
- function Readable(options) {
- Duplex = Duplex || require('./_stream_duplex');
- if (!(this instanceof Readable)) return new Readable(options);
- this._readableState = new ReadableState(options, this);
- // legacy
- this.readable = true;
- if (options) {
- if (typeof options.read === 'function') this._read = options.read;
- if (typeof options.destroy === 'function') this._destroy = options.destroy;
- }
- Stream.call(this);
- }
- Object.defineProperty(Readable.prototype, 'destroyed', {
- get: function () {
- if (this._readableState === undefined) {
- return false;
- }
- return this._readableState.destroyed;
- },
- set: function (value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (!this._readableState) {
- return;
- }
- // backward compatibility, the user is explicitly
- // managing destroyed
- this._readableState.destroyed = value;
- }
- });
- Readable.prototype.destroy = destroyImpl.destroy;
- Readable.prototype._undestroy = destroyImpl.undestroy;
- Readable.prototype._destroy = function (err, cb) {
- this.push(null);
- cb(err);
- };
- // Manually shove something into the read() buffer.
- // This returns true if the highWaterMark has not been hit yet,
- // similar to how Writable.write() returns true if you should
- // write() some more.
- Readable.prototype.push = function (chunk, encoding) {
- var state = this._readableState;
- var skipChunkCheck;
- if (!state.objectMode) {
- if (typeof chunk === 'string') {
- encoding = encoding || state.defaultEncoding;
- if (encoding !== state.encoding) {
- chunk = Buffer.from(chunk, encoding);
- encoding = '';
- }
- skipChunkCheck = true;
- }
- } else {
- skipChunkCheck = true;
- }
- return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
- };
- // Unshift should *always* be something directly out of read()
- Readable.prototype.unshift = function (chunk) {
- return readableAddChunk(this, chunk, null, true, false);
- };
- function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
- var state = stream._readableState;
- if (chunk === null) {
- state.reading = false;
- onEofChunk(stream, state);
- } else {
- var er;
- if (!skipChunkCheck) er = chunkInvalid(state, chunk);
- if (er) {
- stream.emit('error', er);
- } else if (state.objectMode || chunk && chunk.length > 0) {
- if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
- chunk = _uint8ArrayToBuffer(chunk);
- }
- if (addToFront) {
- if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
- } else if (state.ended) {
- stream.emit('error', new Error('stream.push() after EOF'));
- } else {
- state.reading = false;
- if (state.decoder && !encoding) {
- chunk = state.decoder.write(chunk);
- if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
- } else {
- addChunk(stream, state, chunk, false);
- }
- }
- } else if (!addToFront) {
- state.reading = false;
- }
- }
- return needMoreData(state);
- }
- function addChunk(stream, state, chunk, addToFront) {
- if (state.flowing && state.length === 0 && !state.sync) {
- stream.emit('data', chunk);
- stream.read(0);
- } else {
- // update the buffer info.
- state.length += state.objectMode ? 1 : chunk.length;
- if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
- if (state.needReadable) emitReadable(stream);
- }
- maybeReadMore(stream, state);
- }
- function chunkInvalid(state, chunk) {
- var er;
- if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- return er;
- }
- // if it's past the high water mark, we can push in some more.
- // Also, if we have no data yet, we can stand some
- // more bytes. This is to work around cases where hwm=0,
- // such as the repl. Also, if the push() triggered a
- // readable event, and the user called read(largeNumber) such that
- // needReadable was set, then we ought to push more, so that another
- // 'readable' event will be triggered.
- function needMoreData(state) {
- return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
- }
- Readable.prototype.isPaused = function () {
- return this._readableState.flowing === false;
- };
- // backwards compatibility.
- Readable.prototype.setEncoding = function (enc) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this._readableState.decoder = new StringDecoder(enc);
- this._readableState.encoding = enc;
- return this;
- };
- // Don't raise the hwm > 8MB
- var MAX_HWM = 0x800000;
- function computeNewHighWaterMark(n) {
- if (n >= MAX_HWM) {
- n = MAX_HWM;
- } else {
- // Get the next highest power of 2 to prevent increasing hwm excessively in
- // tiny amounts
- n--;
- n |= n >>> 1;
- n |= n >>> 2;
- n |= n >>> 4;
- n |= n >>> 8;
- n |= n >>> 16;
- n++;
- }
- return n;
- }
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function howMuchToRead(n, state) {
- if (n <= 0 || state.length === 0 && state.ended) return 0;
- if (state.objectMode) return 1;
- if (n !== n) {
- // Only flow one buffer at a time
- if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
- }
- // If we're asking for more than the current hwm, then raise the hwm.
- if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
- if (n <= state.length) return n;
- // Don't have enough
- if (!state.ended) {
- state.needReadable = true;
- return 0;
- }
- return state.length;
- }
- // you can override either this method, or the async _read(n) below.
- Readable.prototype.read = function (n) {
- debug('read', n);
- n = parseInt(n, 10);
- var state = this._readableState;
- var nOrig = n;
- if (n !== 0) state.emittedReadable = false;
- // if we're doing read(0) to trigger a readable event, but we
- // already have a bunch of data in the buffer, then just trigger
- // the 'readable' event and move on.
- if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
- debug('read: emitReadable', state.length, state.ended);
- if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
- return null;
- }
- n = howMuchToRead(n, state);
- // if we've ended, and we're now clear, then finish it up.
- if (n === 0 && state.ended) {
- if (state.length === 0) endReadable(this);
- return null;
- }
- // All the actual chunk generation logic needs to be
- // *below* the call to _read. The reason is that in certain
- // synthetic stream cases, such as passthrough streams, _read
- // may be a completely synchronous operation which may change
- // the state of the read buffer, providing enough data when
- // before there was *not* enough.
- //
- // So, the steps are:
- // 1. Figure out what the state of things will be after we do
- // a read from the buffer.
- //
- // 2. If that resulting state will trigger a _read, then call _read.
- // Note that this may be asynchronous, or synchronous. Yes, it is
- // deeply ugly to write APIs this way, but that still doesn't mean
- // that the Readable class should behave improperly, as streams are
- // designed to be sync/async agnostic.
- // Take note if the _read call is sync or async (ie, if the read call
- // has returned yet), so that we know whether or not it's safe to emit
- // 'readable' etc.
- //
- // 3. Actually pull the requested chunks out of the buffer and return.
- // if we need a readable event, then we need to do some reading.
- var doRead = state.needReadable;
- debug('need readable', doRead);
- // if we currently have less than the highWaterMark, then also read some
- if (state.length === 0 || state.length - n < state.highWaterMark) {
- doRead = true;
- debug('length less than watermark', doRead);
- }
- // however, if we've ended, then there's no point, and if we're already
- // reading, then it's unnecessary.
- if (state.ended || state.reading) {
- doRead = false;
- debug('reading or ended', doRead);
- } else if (doRead) {
- debug('do read');
- state.reading = true;
- state.sync = true;
- // if the length is currently zero, then we *need* a readable event.
- if (state.length === 0) state.needReadable = true;
- // call internal read method
- this._read(state.highWaterMark);
- state.sync = false;
- // If _read pushed data synchronously, then `reading` will be false,
- // and we need to re-evaluate how much data we can return to the user.
- if (!state.reading) n = howMuchToRead(nOrig, state);
- }
- var ret;
- if (n > 0) ret = fromList(n, state);else ret = null;
- if (ret === null) {
- state.needReadable = true;
- n = 0;
- } else {
- state.length -= n;
- }
- if (state.length === 0) {
- // If we have nothing in the buffer, then we want to know
- // as soon as we *do* get something into the buffer.
- if (!state.ended) state.needReadable = true;
- // If we tried to read() past the EOF, then emit end on the next tick.
- if (nOrig !== n && state.ended) endReadable(this);
- }
- if (ret !== null) this.emit('data', ret);
- return ret;
- };
- function onEofChunk(stream, state) {
- if (state.ended) return;
- if (state.decoder) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) {
- state.buffer.push(chunk);
- state.length += state.objectMode ? 1 : chunk.length;
- }
- }
- state.ended = true;
- // emit 'readable' now to make sure it gets picked up.
- emitReadable(stream);
- }
- // Don't emit readable right away in sync mode, because this can trigger
- // another read() call => stack overflow. This way, it might trigger
- // a nextTick recursion warning, but that's not so bad.
- function emitReadable(stream) {
- var state = stream._readableState;
- state.needReadable = false;
- if (!state.emittedReadable) {
- debug('emitReadable', state.flowing);
- state.emittedReadable = true;
- if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
- }
- }
- function emitReadable_(stream) {
- debug('emit readable');
- stream.emit('readable');
- flow(stream);
- }
- // at this point, the user has presumably seen the 'readable' event,
- // and called read() to consume some data. that may have triggered
- // in turn another _read(n) call, in which case reading = true if
- // it's in progress.
- // However, if we're not ended, or reading, and the length < hwm,
- // then go ahead and try to read some more preemptively.
- function maybeReadMore(stream, state) {
- if (!state.readingMore) {
- state.readingMore = true;
- pna.nextTick(maybeReadMore_, stream, state);
- }
- }
- function maybeReadMore_(stream, state) {
- var len = state.length;
- while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
- debug('maybeReadMore read 0');
- stream.read(0);
- if (len === state.length)
- // didn't get any data, stop spinning.
- break;else len = state.length;
- }
- state.readingMore = false;
- }
- // abstract method. to be overridden in specific implementation classes.
- // call cb(er, data) where data is <= n in length.
- // for virtual (non-string, non-buffer) streams, "length" is somewhat
- // arbitrary, and perhaps not very meaningful.
- Readable.prototype._read = function (n) {
- this.emit('error', new Error('_read() is not implemented'));
- };
- Readable.prototype.pipe = function (dest, pipeOpts) {
- var src = this;
- var state = this._readableState;
- switch (state.pipesCount) {
- case 0:
- state.pipes = dest;
- break;
- case 1:
- state.pipes = [state.pipes, dest];
- break;
- default:
- state.pipes.push(dest);
- break;
- }
- state.pipesCount += 1;
- debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
- var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
- var endFn = doEnd ? onend : unpipe;
- if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
- dest.on('unpipe', onunpipe);
- function onunpipe(readable, unpipeInfo) {
- debug('onunpipe');
- if (readable === src) {
- if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
- unpipeInfo.hasUnpiped = true;
- cleanup();
- }
- }
- }
- function onend() {
- debug('onend');
- dest.end();
- }
- // when the dest drains, it reduces the awaitDrain counter
- // on the source. This would be more elegant with a .once()
- // handler in flow(), but adding and removing repeatedly is
- // too slow.
- var ondrain = pipeOnDrain(src);
- dest.on('drain', ondrain);
- var cleanedUp = false;
- function cleanup() {
- debug('cleanup');
- // cleanup event handlers once the pipe is broken
- dest.removeListener('close', onclose);
- dest.removeListener('finish', onfinish);
- dest.removeListener('drain', ondrain);
- dest.removeListener('error', onerror);
- dest.removeListener('unpipe', onunpipe);
- src.removeListener('end', onend);
- src.removeListener('end', unpipe);
- src.removeListener('data', ondata);
- cleanedUp = true;
- // if the reader is waiting for a drain event from this
- // specific writer, then it would cause it to never start
- // flowing again.
- // So, if this is awaiting a drain, then we just call it now.
- // If we don't know, then assume that we are waiting for one.
- if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
- }
- // If the user pushes more data while we're writing to dest then we'll end up
- // in ondata again. However, we only want to increase awaitDrain once because
- // dest will only emit one 'drain' event for the multiple writes.
- // => Introduce a guard on increasing awaitDrain.
- var increasedAwaitDrain = false;
- src.on('data', ondata);
- function ondata(chunk) {
- debug('ondata');
- increasedAwaitDrain = false;
- var ret = dest.write(chunk);
- if (false === ret && !increasedAwaitDrain) {
- // If the user unpiped during `dest.write()`, it is possible
- // to get stuck in a permanently paused state if that write
- // also returned false.
- // => Check whether `dest` is still a piping destination.
- if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
- debug('false write response, pause', src._readableState.awaitDrain);
- src._readableState.awaitDrain++;
- increasedAwaitDrain = true;
- }
- src.pause();
- }
- }
- // if the dest has an error, then stop piping into it.
- // however, don't suppress the throwing behavior for this.
- function onerror(er) {
- debug('onerror', er);
- unpipe();
- dest.removeListener('error', onerror);
- if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
- }
- // Make sure our error handler is attached before userland ones.
- prependListener(dest, 'error', onerror);
- // Both close and finish should trigger unpipe, but only once.
- function onclose() {
- dest.removeListener('finish', onfinish);
- unpipe();
- }
- dest.once('close', onclose);
- function onfinish() {
- debug('onfinish');
- dest.removeListener('close', onclose);
- unpipe();
- }
- dest.once('finish', onfinish);
- function unpipe() {
- debug('unpipe');
- src.unpipe(dest);
- }
- // tell the dest that it's being piped to
- dest.emit('pipe', src);
- // start the flow if it hasn't been started already.
- if (!state.flowing) {
- debug('pipe resume');
- src.resume();
- }
- return dest;
- };
- function pipeOnDrain(src) {
- return function () {
- var state = src._readableState;
- debug('pipeOnDrain', state.awaitDrain);
- if (state.awaitDrain) state.awaitDrain--;
- if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
- state.flowing = true;
- flow(src);
- }
- };
- }
- Readable.prototype.unpipe = function (dest) {
- var state = this._readableState;
- var unpipeInfo = { hasUnpiped: false };
- // if we're not piping anywhere, then do nothing.
- if (state.pipesCount === 0) return this;
- // just one destination. most common case.
- if (state.pipesCount === 1) {
- // passed in one, but it's not the right one.
- if (dest && dest !== state.pipes) return this;
- if (!dest) dest = state.pipes;
- // got a match.
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
- if (dest) dest.emit('unpipe', this, unpipeInfo);
- return this;
- }
- // slow case. multiple pipe destinations.
- if (!dest) {
- // remove all.
- var dests = state.pipes;
- var len = state.pipesCount;
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
- for (var i = 0; i < len; i++) {
- dests[i].emit('unpipe', this, unpipeInfo);
- }return this;
- }
- // try to find the right one.
- var index = indexOf(state.pipes, dest);
- if (index === -1) return this;
- state.pipes.splice(index, 1);
- state.pipesCount -= 1;
- if (state.pipesCount === 1) state.pipes = state.pipes[0];
- dest.emit('unpipe', this, unpipeInfo);
- return this;
- };
- // set up data events if they are asked for
- // Ensure readable listeners eventually get something
- Readable.prototype.on = function (ev, fn) {
- var res = Stream.prototype.on.call(this, ev, fn);
- if (ev === 'data') {
- // Start flowing on next tick if stream isn't explicitly paused
- if (this._readableState.flowing !== false) this.resume();
- } else if (ev === 'readable') {
- var state = this._readableState;
- if (!state.endEmitted && !state.readableListening) {
- state.readableListening = state.needReadable = true;
- state.emittedReadable = false;
- if (!state.reading) {
- pna.nextTick(nReadingNextTick, this);
- } else if (state.length) {
- emitReadable(this);
- }
- }
- }
- return res;
- };
- Readable.prototype.addListener = Readable.prototype.on;
- function nReadingNextTick(self) {
- debug('readable nexttick read 0');
- self.read(0);
- }
- // pause() and resume() are remnants of the legacy readable stream API
- // If the user uses them, then switch into old mode.
- Readable.prototype.resume = function () {
- var state = this._readableState;
- if (!state.flowing) {
- debug('resume');
- state.flowing = true;
- resume(this, state);
- }
- return this;
- };
- function resume(stream, state) {
- if (!state.resumeScheduled) {
- state.resumeScheduled = true;
- pna.nextTick(resume_, stream, state);
- }
- }
- function resume_(stream, state) {
- if (!state.reading) {
- debug('resume read 0');
- stream.read(0);
- }
- state.resumeScheduled = false;
- state.awaitDrain = 0;
- stream.emit('resume');
- flow(stream);
- if (state.flowing && !state.reading) stream.read(0);
- }
- Readable.prototype.pause = function () {
- debug('call pause flowing=%j', this._readableState.flowing);
- if (false !== this._readableState.flowing) {
- debug('pause');
- this._readableState.flowing = false;
- this.emit('pause');
- }
- return this;
- };
- function flow(stream) {
- var state = stream._readableState;
- debug('flow', state.flowing);
- while (state.flowing && stream.read() !== null) {}
- }
- // wrap an old-style stream as the async data source.
- // This is *not* part of the readable stream interface.
- // It is an ugly unfortunate mess of history.
- Readable.prototype.wrap = function (stream) {
- var _this = this;
- var state = this._readableState;
- var paused = false;
- stream.on('end', function () {
- debug('wrapped end');
- if (state.decoder && !state.ended) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) _this.push(chunk);
- }
- _this.push(null);
- });
- stream.on('data', function (chunk) {
- debug('wrapped data');
- if (state.decoder) chunk = state.decoder.write(chunk);
- // don't skip over falsy values in objectMode
- if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
- var ret = _this.push(chunk);
- if (!ret) {
- paused = true;
- stream.pause();
- }
- });
- // proxy all the other methods.
- // important when wrapping filters and duplexes.
- for (var i in stream) {
- if (this[i] === undefined && typeof stream[i] === 'function') {
- this[i] = function (method) {
- return function () {
- return stream[method].apply(stream, arguments);
- };
- }(i);
- }
- }
- // proxy certain important events.
- for (var n = 0; n < kProxyEvents.length; n++) {
- stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
- }
- // when we try to consume some more bytes, simply unpause the
- // underlying stream.
- this._read = function (n) {
- debug('wrapped _read', n);
- if (paused) {
- paused = false;
- stream.resume();
- }
- };
- return this;
- };
- Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function () {
- return this._readableState.highWaterMark;
- }
- });
- // exposed for testing purposes only.
- Readable._fromList = fromList;
- // Pluck off n bytes from an array of buffers.
- // Length is the combined lengths of all the buffers in the list.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function fromList(n, state) {
- // nothing buffered
- if (state.length === 0) return null;
- var ret;
- if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
- // read it all, truncate the list
- 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);
- state.buffer.clear();
- } else {
- // read part of list
- ret = fromListPartial(n, state.buffer, state.decoder);
- }
- return ret;
- }
- // Extracts only enough buffered data to satisfy the amount requested.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function fromListPartial(n, list, hasStrings) {
- var ret;
- if (n < list.head.data.length) {
- // slice is the same for buffers and strings
- ret = list.head.data.slice(0, n);
- list.head.data = list.head.data.slice(n);
- } else if (n === list.head.data.length) {
- // first chunk is a perfect match
- ret = list.shift();
- } else {
- // result spans more than one buffer
- ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
- }
- return ret;
- }
- // Copies a specified amount of characters from the list of buffered data
- // chunks.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function copyFromBufferString(n, list) {
- var p = list.head;
- var c = 1;
- var ret = p.data;
- n -= ret.length;
- while (p = p.next) {
- var str = p.data;
- var nb = n > str.length ? str.length : n;
- if (nb === str.length) ret += str;else ret += str.slice(0, n);
- n -= nb;
- if (n === 0) {
- if (nb === str.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = str.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
- }
- // Copies a specified amount of bytes from the list of buffered data chunks.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function copyFromBuffer(n, list) {
- var ret = Buffer.allocUnsafe(n);
- var p = list.head;
- var c = 1;
- p.data.copy(ret);
- n -= p.data.length;
- while (p = p.next) {
- var buf = p.data;
- var nb = n > buf.length ? buf.length : n;
- buf.copy(ret, ret.length - n, 0, nb);
- n -= nb;
- if (n === 0) {
- if (nb === buf.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = buf.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
- }
- function endReadable(stream) {
- var state = stream._readableState;
- // If we get here before consuming all the bytes, then that is a
- // bug in node. Should never happen.
- if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
- if (!state.endEmitted) {
- state.ended = true;
- pna.nextTick(endReadableNT, state, stream);
- }
- }
- function endReadableNT(state, stream) {
- // Check that we didn't get one last unshift.
- if (!state.endEmitted && state.length === 0) {
- state.endEmitted = true;
- stream.readable = false;
- stream.emit('end');
- }
- }
- function indexOf(xs, x) {
- for (var i = 0, l = xs.length; i < l; i++) {
- if (xs[i] === x) return i;
- }
- return -1;
- }
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./_stream_duplex":318,"./internal/streams/BufferList":323,"./internal/streams/destroy":324,"./internal/streams/stream":325,"_process":312,"core-util-is":238,"events":239,"inherits":254,"isarray":258,"process-nextick-args":311,"safe-buffer":326,"string_decoder/":327,"util":32}],321:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // a transform stream is a readable/writable stream where you do
- // something with the data. Sometimes it's called a "filter",
- // but that's not a great name for it, since that implies a thing where
- // some bits pass through, and others are simply ignored. (That would
- // be a valid example of a transform, of course.)
- //
- // While the output is causally related to the input, it's not a
- // necessarily symmetric or synchronous transformation. For example,
- // a zlib stream might take multiple plain-text writes(), and then
- // emit a single compressed chunk some time in the future.
- //
- // Here's how this works:
- //
- // The Transform stream has all the aspects of the readable and writable
- // stream classes. When you write(chunk), that calls _write(chunk,cb)
- // internally, and returns false if there's a lot of pending writes
- // buffered up. When you call read(), that calls _read(n) until
- // there's enough pending readable data buffered up.
- //
- // In a transform stream, the written data is placed in a buffer. When
- // _read(n) is called, it transforms the queued up data, calling the
- // buffered _write cb's as it consumes chunks. If consuming a single
- // written chunk would result in multiple output chunks, then the first
- // outputted bit calls the readcb, and subsequent chunks just go into
- // the read buffer, and will cause it to emit 'readable' if necessary.
- //
- // This way, back-pressure is actually determined by the reading side,
- // since _read has to be called to start processing a new chunk. However,
- // a pathological inflate type of transform can cause excessive buffering
- // here. For example, imagine a stream where every byte of input is
- // interpreted as an integer from 0-255, and then results in that many
- // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
- // 1kb of data being output. In this case, you could write a very small
- // amount of input, and end up with a very large amount of output. In
- // such a pathological inflating mechanism, there'd be no way to tell
- // the system to stop doing the transform. A single 4MB write could
- // cause the system to run out of memory.
- //
- // However, even in such a pathological case, only a single written chunk
- // would be consumed, and then the rest would wait (un-transformed) until
- // the results of the previous transformed chunk were consumed.
- 'use strict';
- module.exports = Transform;
- var Duplex = require('./_stream_duplex');
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
- util.inherits(Transform, Duplex);
- function afterTransform(er, data) {
- var ts = this._transformState;
- ts.transforming = false;
- var cb = ts.writecb;
- if (!cb) {
- return this.emit('error', new Error('write callback called multiple times'));
- }
- ts.writechunk = null;
- ts.writecb = null;
- if (data != null) // single equals check for both `null` and `undefined`
- this.push(data);
- cb(er);
- var rs = this._readableState;
- rs.reading = false;
- if (rs.needReadable || rs.length < rs.highWaterMark) {
- this._read(rs.highWaterMark);
- }
- }
- function Transform(options) {
- if (!(this instanceof Transform)) return new Transform(options);
- Duplex.call(this, options);
- this._transformState = {
- afterTransform: afterTransform.bind(this),
- needTransform: false,
- transforming: false,
- writecb: null,
- writechunk: null,
- writeencoding: null
- };
- // start out asking for a readable event once data is transformed.
- this._readableState.needReadable = true;
- // we have implemented the _read method, and done the other things
- // that Readable wants before the first _read call, so unset the
- // sync guard flag.
- this._readableState.sync = false;
- if (options) {
- if (typeof options.transform === 'function') this._transform = options.transform;
- if (typeof options.flush === 'function') this._flush = options.flush;
- }
- // When the writable side finishes, then flush out anything remaining.
- this.on('prefinish', prefinish);
- }
- function prefinish() {
- var _this = this;
- if (typeof this._flush === 'function') {
- this._flush(function (er, data) {
- done(_this, er, data);
- });
- } else {
- done(this, null, null);
- }
- }
- Transform.prototype.push = function (chunk, encoding) {
- this._transformState.needTransform = false;
- return Duplex.prototype.push.call(this, chunk, encoding);
- };
- // This is the part where you do stuff!
- // override this function in implementation classes.
- // 'chunk' is an input chunk.
- //
- // Call `push(newChunk)` to pass along transformed output
- // to the readable side. You may call 'push' zero or more times.
- //
- // Call `cb(err)` when you are done with this chunk. If you pass
- // an error, then that'll put the hurt on the whole operation. If you
- // never call cb(), then you'll never get another chunk.
- Transform.prototype._transform = function (chunk, encoding, cb) {
- throw new Error('_transform() is not implemented');
- };
- Transform.prototype._write = function (chunk, encoding, cb) {
- var ts = this._transformState;
- ts.writecb = cb;
- ts.writechunk = chunk;
- ts.writeencoding = encoding;
- if (!ts.transforming) {
- var rs = this._readableState;
- if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
- }
- };
- // Doesn't matter what the args are here.
- // _transform does all the work.
- // That we got here means that the readable side wants more data.
- Transform.prototype._read = function (n) {
- var ts = this._transformState;
- if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
- ts.transforming = true;
- this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
- } else {
- // mark that we need a transform, so that any data that comes in
- // will get processed, now that we've asked for it.
- ts.needTransform = true;
- }
- };
- Transform.prototype._destroy = function (err, cb) {
- var _this2 = this;
- Duplex.prototype._destroy.call(this, err, function (err2) {
- cb(err2);
- _this2.emit('close');
- });
- };
- function done(stream, er, data) {
- if (er) return stream.emit('error', er);
- if (data != null) // single equals check for both `null` and `undefined`
- stream.push(data);
- // if there's nothing in the write buffer, then that means
- // that nothing more will ever be provided
- if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
- if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
- return stream.push(null);
- }
- },{"./_stream_duplex":318,"core-util-is":238,"inherits":254}],322:[function(require,module,exports){
- (function (process,global,setImmediate){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // A bit simpler than readable streams.
- // Implement an async ._write(chunk, encoding, cb), and it'll handle all
- // the drain event emission and buffering.
- 'use strict';
- /*<replacement>*/
- var pna = require('process-nextick-args');
- /*</replacement>*/
- module.exports = Writable;
- /* <replacement> */
- function WriteReq(chunk, encoding, cb) {
- this.chunk = chunk;
- this.encoding = encoding;
- this.callback = cb;
- this.next = null;
- }
- // It seems a linked list but it is not
- // there will be only 2 of these for each stream
- function CorkedRequest(state) {
- var _this = this;
- this.next = null;
- this.entry = null;
- this.finish = function () {
- onCorkedFinish(_this, state);
- };
- }
- /* </replacement> */
- /*<replacement>*/
- var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
- /*</replacement>*/
- /*<replacement>*/
- var Duplex;
- /*</replacement>*/
- Writable.WritableState = WritableState;
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
- /*<replacement>*/
- var internalUtil = {
- deprecate: require('util-deprecate')
- };
- /*</replacement>*/
- /*<replacement>*/
- var Stream = require('./internal/streams/stream');
- /*</replacement>*/
- /*<replacement>*/
- var Buffer = require('safe-buffer').Buffer;
- var OurUint8Array = global.Uint8Array || function () {};
- function _uint8ArrayToBuffer(chunk) {
- return Buffer.from(chunk);
- }
- function _isUint8Array(obj) {
- return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
- }
- /*</replacement>*/
- var destroyImpl = require('./internal/streams/destroy');
- util.inherits(Writable, Stream);
- function nop() {}
- function WritableState(options, stream) {
- Duplex = Duplex || require('./_stream_duplex');
- options = options || {};
- // Duplex streams are both readable and writable, but share
- // the same options object.
- // However, some cases require setting options to different
- // values for the readable and the writable sides of the duplex stream.
- // These options can be provided separately as readableXXX and writableXXX.
- var isDuplex = stream instanceof Duplex;
- // object stream flag to indicate whether or not this stream
- // contains buffers or objects.
- this.objectMode = !!options.objectMode;
- if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
- // the point at which write() starts returning false
- // Note: 0 is a valid value, means that we always return false if
- // the entire buffer is not flushed immediately on write()
- var hwm = options.highWaterMark;
- var writableHwm = options.writableHighWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
- if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
- // cast to ints.
- this.highWaterMark = Math.floor(this.highWaterMark);
- // if _final has been called
- this.finalCalled = false;
- // drain event flag.
- this.needDrain = false;
- // at the start of calling end()
- this.ending = false;
- // when end() has been called, and returned
- this.ended = false;
- // when 'finish' is emitted
- this.finished = false;
- // has it been destroyed
- this.destroyed = false;
- // should we decode strings into buffers before passing to _write?
- // this is here so that some node-core streams can optimize string
- // handling at a lower level.
- var noDecode = options.decodeStrings === false;
- this.decodeStrings = !noDecode;
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
- // not an actual buffer we keep track of, but a measurement
- // of how much we're waiting to get pushed to some underlying
- // socket or file.
- this.length = 0;
- // a flag to see when we're in the middle of a write.
- this.writing = false;
- // when true all writes will be buffered until .uncork() call
- this.corked = 0;
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
- // a flag to know if we're processing previously buffered items, which
- // may call the _write() callback in the same tick, so that we don't
- // end up in an overlapped onwrite situation.
- this.bufferProcessing = false;
- // the callback that's passed to _write(chunk,cb)
- this.onwrite = function (er) {
- onwrite(stream, er);
- };
- // the callback that the user supplies to write(chunk,encoding,cb)
- this.writecb = null;
- // the amount that is being written when _write is called.
- this.writelen = 0;
- this.bufferedRequest = null;
- this.lastBufferedRequest = null;
- // number of pending user-supplied write callbacks
- // this must be 0 before 'finish' can be emitted
- this.pendingcb = 0;
- // emit prefinish if the only thing we're waiting for is _write cbs
- // This is relevant for synchronous Transform streams
- this.prefinished = false;
- // True if the error was already emitted and should not be thrown again
- this.errorEmitted = false;
- // count buffered requests
- this.bufferedRequestCount = 0;
- // allocate the first CorkedRequest, there is always
- // one allocated and free to use, and we maintain at most two
- this.corkedRequestsFree = new CorkedRequest(this);
- }
- WritableState.prototype.getBuffer = function getBuffer() {
- var current = this.bufferedRequest;
- var out = [];
- while (current) {
- out.push(current);
- current = current.next;
- }
- return out;
- };
- (function () {
- try {
- Object.defineProperty(WritableState.prototype, 'buffer', {
- get: internalUtil.deprecate(function () {
- return this.getBuffer();
- }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
- });
- } catch (_) {}
- })();
- // Test _writableState for inheritance to account for Duplex streams,
- // whose prototype chain only points to Readable.
- var realHasInstance;
- if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
- realHasInstance = Function.prototype[Symbol.hasInstance];
- Object.defineProperty(Writable, Symbol.hasInstance, {
- value: function (object) {
- if (realHasInstance.call(this, object)) return true;
- if (this !== Writable) return false;
- return object && object._writableState instanceof WritableState;
- }
- });
- } else {
- realHasInstance = function (object) {
- return object instanceof this;
- };
- }
- function Writable(options) {
- Duplex = Duplex || require('./_stream_duplex');
- // Writable ctor is applied to Duplexes, too.
- // `realHasInstance` is necessary because using plain `instanceof`
- // would return false, as no `_writableState` property is attached.
- // Trying to use the custom `instanceof` for Writable here will also break the
- // Node.js LazyTransform implementation, which has a non-trivial getter for
- // `_writableState` that would lead to infinite recursion.
- if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
- return new Writable(options);
- }
- this._writableState = new WritableState(options, this);
- // legacy.
- this.writable = true;
- if (options) {
- if (typeof options.write === 'function') this._write = options.write;
- if (typeof options.writev === 'function') this._writev = options.writev;
- if (typeof options.destroy === 'function') this._destroy = options.destroy;
- if (typeof options.final === 'function') this._final = options.final;
- }
- Stream.call(this);
- }
- // Otherwise people can pipe Writable streams, which is just wrong.
- Writable.prototype.pipe = function () {
- this.emit('error', new Error('Cannot pipe, not readable'));
- };
- function writeAfterEnd(stream, cb) {
- var er = new Error('write after end');
- // TODO: defer error events consistently everywhere, not just the cb
- stream.emit('error', er);
- pna.nextTick(cb, er);
- }
- // Checks that a user-supplied chunk is valid, especially for the particular
- // mode the stream is in. Currently this means that `null` is never accepted
- // and undefined/non-string values are only allowed in object mode.
- function validChunk(stream, state, chunk, cb) {
- var valid = true;
- var er = false;
- if (chunk === null) {
- er = new TypeError('May not write null values to stream');
- } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- if (er) {
- stream.emit('error', er);
- pna.nextTick(cb, er);
- valid = false;
- }
- return valid;
- }
- Writable.prototype.write = function (chunk, encoding, cb) {
- var state = this._writableState;
- var ret = false;
- var isBuf = !state.objectMode && _isUint8Array(chunk);
- if (isBuf && !Buffer.isBuffer(chunk)) {
- chunk = _uint8ArrayToBuffer(chunk);
- }
- if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
- if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
- if (typeof cb !== 'function') cb = nop;
- if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
- state.pendingcb++;
- ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
- }
- return ret;
- };
- Writable.prototype.cork = function () {
- var state = this._writableState;
- state.corked++;
- };
- Writable.prototype.uncork = function () {
- var state = this._writableState;
- if (state.corked) {
- state.corked--;
- if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
- }
- };
- Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
- // node::ParseEncoding() requires lower case.
- if (typeof encoding === 'string') encoding = encoding.toLowerCase();
- 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);
- this._writableState.defaultEncoding = encoding;
- return this;
- };
- function decodeChunk(state, chunk, encoding) {
- if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
- chunk = Buffer.from(chunk, encoding);
- }
- return chunk;
- }
- Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function () {
- return this._writableState.highWaterMark;
- }
- });
- // if we're already writing something, then just put this
- // in the queue, and wait our turn. Otherwise, call _write
- // If we return false, then we need a drain event, so set that flag.
- function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
- if (!isBuf) {
- var newChunk = decodeChunk(state, chunk, encoding);
- if (chunk !== newChunk) {
- isBuf = true;
- encoding = 'buffer';
- chunk = newChunk;
- }
- }
- var len = state.objectMode ? 1 : chunk.length;
- state.length += len;
- var ret = state.length < state.highWaterMark;
- // we must ensure that previous needDrain will not be reset to false.
- if (!ret) state.needDrain = true;
- if (state.writing || state.corked) {
- var last = state.lastBufferedRequest;
- state.lastBufferedRequest = {
- chunk: chunk,
- encoding: encoding,
- isBuf: isBuf,
- callback: cb,
- next: null
- };
- if (last) {
- last.next = state.lastBufferedRequest;
- } else {
- state.bufferedRequest = state.lastBufferedRequest;
- }
- state.bufferedRequestCount += 1;
- } else {
- doWrite(stream, state, false, len, chunk, encoding, cb);
- }
- return ret;
- }
- function doWrite(stream, state, writev, len, chunk, encoding, cb) {
- state.writelen = len;
- state.writecb = cb;
- state.writing = true;
- state.sync = true;
- if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
- state.sync = false;
- }
- function onwriteError(stream, state, sync, er, cb) {
- --state.pendingcb;
- if (sync) {
- // defer the callback if we are being called synchronously
- // to avoid piling up things on the stack
- pna.nextTick(cb, er);
- // this can emit finish, and it will always happen
- // after error
- pna.nextTick(finishMaybe, stream, state);
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
- } else {
- // the caller expect this to happen before if
- // it is async
- cb(er);
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
- // this can emit finish, but finish must
- // always follow error
- finishMaybe(stream, state);
- }
- }
- function onwriteStateUpdate(state) {
- state.writing = false;
- state.writecb = null;
- state.length -= state.writelen;
- state.writelen = 0;
- }
- function onwrite(stream, er) {
- var state = stream._writableState;
- var sync = state.sync;
- var cb = state.writecb;
- onwriteStateUpdate(state);
- if (er) onwriteError(stream, state, sync, er, cb);else {
- // Check if we're actually ready to finish, but don't emit yet
- var finished = needFinish(state);
- if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
- clearBuffer(stream, state);
- }
- if (sync) {
- /*<replacement>*/
- asyncWrite(afterWrite, stream, state, finished, cb);
- /*</replacement>*/
- } else {
- afterWrite(stream, state, finished, cb);
- }
- }
- }
- function afterWrite(stream, state, finished, cb) {
- if (!finished) onwriteDrain(stream, state);
- state.pendingcb--;
- cb();
- finishMaybe(stream, state);
- }
- // Must force callback to be called on nextTick, so that we don't
- // emit 'drain' before the write() consumer gets the 'false' return
- // value, and has a chance to attach a 'drain' listener.
- function onwriteDrain(stream, state) {
- if (state.length === 0 && state.needDrain) {
- state.needDrain = false;
- stream.emit('drain');
- }
- }
- // if there's something in the buffer waiting, then process it
- function clearBuffer(stream, state) {
- state.bufferProcessing = true;
- var entry = state.bufferedRequest;
- if (stream._writev && entry && entry.next) {
- // Fast case, write everything using _writev()
- var l = state.bufferedRequestCount;
- var buffer = new Array(l);
- var holder = state.corkedRequestsFree;
- holder.entry = entry;
- var count = 0;
- var allBuffers = true;
- while (entry) {
- buffer[count] = entry;
- if (!entry.isBuf) allBuffers = false;
- entry = entry.next;
- count += 1;
- }
- buffer.allBuffers = allBuffers;
- doWrite(stream, state, true, state.length, buffer, '', holder.finish);
- // doWrite is almost always async, defer these to save a bit of time
- // as the hot path ends with doWrite
- state.pendingcb++;
- state.lastBufferedRequest = null;
- if (holder.next) {
- state.corkedRequestsFree = holder.next;
- holder.next = null;
- } else {
- state.corkedRequestsFree = new CorkedRequest(state);
- }
- state.bufferedRequestCount = 0;
- } else {
- // Slow case, write chunks one-by-one
- while (entry) {
- var chunk = entry.chunk;
- var encoding = entry.encoding;
- var cb = entry.callback;
- var len = state.objectMode ? 1 : chunk.length;
- doWrite(stream, state, false, len, chunk, encoding, cb);
- entry = entry.next;
- state.bufferedRequestCount--;
- // if we didn't call the onwrite immediately, then
- // it means that we need to wait until it does.
- // also, that means that the chunk and cb are currently
- // being processed, so move the buffer counter past them.
- if (state.writing) {
- break;
- }
- }
- if (entry === null) state.lastBufferedRequest = null;
- }
- state.bufferedRequest = entry;
- state.bufferProcessing = false;
- }
- Writable.prototype._write = function (chunk, encoding, cb) {
- cb(new Error('_write() is not implemented'));
- };
- Writable.prototype._writev = null;
- Writable.prototype.end = function (chunk, encoding, cb) {
- var state = this._writableState;
- if (typeof chunk === 'function') {
- cb = chunk;
- chunk = null;
- encoding = null;
- } else if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
- if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
- // .end() fully uncorks
- if (state.corked) {
- state.corked = 1;
- this.uncork();
- }
- // ignore unnecessary end() calls.
- if (!state.ending && !state.finished) endWritable(this, state, cb);
- };
- function needFinish(state) {
- return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
- }
- function callFinal(stream, state) {
- stream._final(function (err) {
- state.pendingcb--;
- if (err) {
- stream.emit('error', err);
- }
- state.prefinished = true;
- stream.emit('prefinish');
- finishMaybe(stream, state);
- });
- }
- function prefinish(stream, state) {
- if (!state.prefinished && !state.finalCalled) {
- if (typeof stream._final === 'function') {
- state.pendingcb++;
- state.finalCalled = true;
- pna.nextTick(callFinal, stream, state);
- } else {
- state.prefinished = true;
- stream.emit('prefinish');
- }
- }
- }
- function finishMaybe(stream, state) {
- var need = needFinish(state);
- if (need) {
- prefinish(stream, state);
- if (state.pendingcb === 0) {
- state.finished = true;
- stream.emit('finish');
- }
- }
- return need;
- }
- function endWritable(stream, state, cb) {
- state.ending = true;
- finishMaybe(stream, state);
- if (cb) {
- if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
- }
- state.ended = true;
- stream.writable = false;
- }
- function onCorkedFinish(corkReq, state, err) {
- var entry = corkReq.entry;
- corkReq.entry = null;
- while (entry) {
- var cb = entry.callback;
- state.pendingcb--;
- cb(err);
- entry = entry.next;
- }
- if (state.corkedRequestsFree) {
- state.corkedRequestsFree.next = corkReq;
- } else {
- state.corkedRequestsFree = corkReq;
- }
- }
- Object.defineProperty(Writable.prototype, 'destroyed', {
- get: function () {
- if (this._writableState === undefined) {
- return false;
- }
- return this._writableState.destroyed;
- },
- set: function (value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (!this._writableState) {
- return;
- }
- // backward compatibility, the user is explicitly
- // managing destroyed
- this._writableState.destroyed = value;
- }
- });
- Writable.prototype.destroy = destroyImpl.destroy;
- Writable.prototype._undestroy = destroyImpl.undestroy;
- Writable.prototype._destroy = function (err, cb) {
- this.end();
- cb(err);
- };
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
- },{"./_stream_duplex":318,"./internal/streams/destroy":324,"./internal/streams/stream":325,"_process":312,"core-util-is":238,"inherits":254,"process-nextick-args":311,"safe-buffer":326,"timers":355,"util-deprecate":362}],323:[function(require,module,exports){
- 'use strict';
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var Buffer = require('safe-buffer').Buffer;
- var util = require('util');
- function copyBuffer(src, target, offset) {
- src.copy(target, offset);
- }
- module.exports = function () {
- function BufferList() {
- _classCallCheck(this, BufferList);
- this.head = null;
- this.tail = null;
- this.length = 0;
- }
- BufferList.prototype.push = function push(v) {
- var entry = { data: v, next: null };
- if (this.length > 0) this.tail.next = entry;else this.head = entry;
- this.tail = entry;
- ++this.length;
- };
- BufferList.prototype.unshift = function unshift(v) {
- var entry = { data: v, next: this.head };
- if (this.length === 0) this.tail = entry;
- this.head = entry;
- ++this.length;
- };
- BufferList.prototype.shift = function shift() {
- if (this.length === 0) return;
- var ret = this.head.data;
- if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
- --this.length;
- return ret;
- };
- BufferList.prototype.clear = function clear() {
- this.head = this.tail = null;
- this.length = 0;
- };
- BufferList.prototype.join = function join(s) {
- if (this.length === 0) return '';
- var p = this.head;
- var ret = '' + p.data;
- while (p = p.next) {
- ret += s + p.data;
- }return ret;
- };
- BufferList.prototype.concat = function concat(n) {
- if (this.length === 0) return Buffer.alloc(0);
- if (this.length === 1) return this.head.data;
- var ret = Buffer.allocUnsafe(n >>> 0);
- var p = this.head;
- var i = 0;
- while (p) {
- copyBuffer(p.data, ret, i);
- i += p.data.length;
- p = p.next;
- }
- return ret;
- };
- return BufferList;
- }();
- if (util && util.inspect && util.inspect.custom) {
- module.exports.prototype[util.inspect.custom] = function () {
- var obj = util.inspect({ length: this.length });
- return this.constructor.name + ' ' + obj;
- };
- }
- },{"safe-buffer":326,"util":32}],324:[function(require,module,exports){
- 'use strict';
- /*<replacement>*/
- var pna = require('process-nextick-args');
- /*</replacement>*/
- // undocumented cb() API, needed for core, not for public API
- function destroy(err, cb) {
- var _this = this;
- var readableDestroyed = this._readableState && this._readableState.destroyed;
- var writableDestroyed = this._writableState && this._writableState.destroyed;
- if (readableDestroyed || writableDestroyed) {
- if (cb) {
- cb(err);
- } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
- pna.nextTick(emitErrorNT, this, err);
- }
- return this;
- }
- // we set destroyed to true before firing error callbacks in order
- // to make it re-entrance safe in case destroy() is called within callbacks
- if (this._readableState) {
- this._readableState.destroyed = true;
- }
- // if this is a duplex stream mark the writable part as destroyed as well
- if (this._writableState) {
- this._writableState.destroyed = true;
- }
- this._destroy(err || null, function (err) {
- if (!cb && err) {
- pna.nextTick(emitErrorNT, _this, err);
- if (_this._writableState) {
- _this._writableState.errorEmitted = true;
- }
- } else if (cb) {
- cb(err);
- }
- });
- return this;
- }
- function undestroy() {
- if (this._readableState) {
- this._readableState.destroyed = false;
- this._readableState.reading = false;
- this._readableState.ended = false;
- this._readableState.endEmitted = false;
- }
- if (this._writableState) {
- this._writableState.destroyed = false;
- this._writableState.ended = false;
- this._writableState.ending = false;
- this._writableState.finished = false;
- this._writableState.errorEmitted = false;
- }
- }
- function emitErrorNT(self, err) {
- self.emit('error', err);
- }
- module.exports = {
- destroy: destroy,
- undestroy: undestroy
- };
- },{"process-nextick-args":311}],325:[function(require,module,exports){
- module.exports = require('events').EventEmitter;
- },{"events":239}],326:[function(require,module,exports){
- /* eslint-disable node/no-deprecated-api */
- var buffer = require('buffer')
- var Buffer = buffer.Buffer
- // alternative to using Object.keys for old browsers
- function copyProps (src, dst) {
- for (var key in src) {
- dst[key] = src[key]
- }
- }
- if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
- module.exports = buffer
- } else {
- // Copy properties from require('buffer')
- copyProps(buffer, exports)
- exports.Buffer = SafeBuffer
- }
- function SafeBuffer (arg, encodingOrOffset, length) {
- return Buffer(arg, encodingOrOffset, length)
- }
- // Copy static methods from Buffer
- copyProps(Buffer, SafeBuffer)
- SafeBuffer.from = function (arg, encodingOrOffset, length) {
- if (typeof arg === 'number') {
- throw new TypeError('Argument must not be a number')
- }
- return Buffer(arg, encodingOrOffset, length)
- }
- SafeBuffer.alloc = function (size, fill, encoding) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- var buf = Buffer(size)
- if (fill !== undefined) {
- if (typeof encoding === 'string') {
- buf.fill(fill, encoding)
- } else {
- buf.fill(fill)
- }
- } else {
- buf.fill(0)
- }
- return buf
- }
- SafeBuffer.allocUnsafe = function (size) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- return Buffer(size)
- }
- SafeBuffer.allocUnsafeSlow = function (size) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- return buffer.SlowBuffer(size)
- }
- },{"buffer":47}],327:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- 'use strict';
- /*<replacement>*/
- var Buffer = require('safe-buffer').Buffer;
- /*</replacement>*/
- var isEncoding = Buffer.isEncoding || function (encoding) {
- encoding = '' + encoding;
- switch (encoding && encoding.toLowerCase()) {
- 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;
- default:
- return false;
- }
- };
- function _normalizeEncoding(enc) {
- if (!enc) return 'utf8';
- var retried;
- while (true) {
- switch (enc) {
- case 'utf8':
- case 'utf-8':
- return 'utf8';
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return 'utf16le';
- case 'latin1':
- case 'binary':
- return 'latin1';
- case 'base64':
- case 'ascii':
- case 'hex':
- return enc;
- default:
- if (retried) return; // undefined
- enc = ('' + enc).toLowerCase();
- retried = true;
- }
- }
- };
- // Do not cache `Buffer.isEncoding` when checking encoding names as some
- // modules monkey-patch it to support additional encodings
- function normalizeEncoding(enc) {
- var nenc = _normalizeEncoding(enc);
- if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
- return nenc || enc;
- }
- // StringDecoder provides an interface for efficiently splitting a series of
- // buffers into a series of JS strings without breaking apart multi-byte
- // characters.
- exports.StringDecoder = StringDecoder;
- function StringDecoder(encoding) {
- this.encoding = normalizeEncoding(encoding);
- var nb;
- switch (this.encoding) {
- case 'utf16le':
- this.text = utf16Text;
- this.end = utf16End;
- nb = 4;
- break;
- case 'utf8':
- this.fillLast = utf8FillLast;
- nb = 4;
- break;
- case 'base64':
- this.text = base64Text;
- this.end = base64End;
- nb = 3;
- break;
- default:
- this.write = simpleWrite;
- this.end = simpleEnd;
- return;
- }
- this.lastNeed = 0;
- this.lastTotal = 0;
- this.lastChar = Buffer.allocUnsafe(nb);
- }
- StringDecoder.prototype.write = function (buf) {
- if (buf.length === 0) return '';
- var r;
- var i;
- if (this.lastNeed) {
- r = this.fillLast(buf);
- if (r === undefined) return '';
- i = this.lastNeed;
- this.lastNeed = 0;
- } else {
- i = 0;
- }
- if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
- return r || '';
- };
- StringDecoder.prototype.end = utf8End;
- // Returns only complete characters in a Buffer
- StringDecoder.prototype.text = utf8Text;
- // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
- StringDecoder.prototype.fillLast = function (buf) {
- if (this.lastNeed <= buf.length) {
- buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
- return this.lastChar.toString(this.encoding, 0, this.lastTotal);
- }
- buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
- this.lastNeed -= buf.length;
- };
- // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
- // continuation byte. If an invalid byte is detected, -2 is returned.
- function utf8CheckByte(byte) {
- if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
- return byte >> 6 === 0x02 ? -1 : -2;
- }
- // Checks at most 3 bytes at the end of a Buffer in order to detect an
- // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
- // needed to complete the UTF-8 character (if applicable) are returned.
- function utf8CheckIncomplete(self, buf, i) {
- var j = buf.length - 1;
- if (j < i) return 0;
- var nb = utf8CheckByte(buf[j]);
- if (nb >= 0) {
- if (nb > 0) self.lastNeed = nb - 1;
- return nb;
- }
- if (--j < i || nb === -2) return 0;
- nb = utf8CheckByte(buf[j]);
- if (nb >= 0) {
- if (nb > 0) self.lastNeed = nb - 2;
- return nb;
- }
- if (--j < i || nb === -2) return 0;
- nb = utf8CheckByte(buf[j]);
- if (nb >= 0) {
- if (nb > 0) {
- if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
- }
- return nb;
- }
- return 0;
- }
- // Validates as many continuation bytes for a multi-byte UTF-8 character as
- // needed or are available. If we see a non-continuation byte where we expect
- // one, we "replace" the validated continuation bytes we've seen so far with
- // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
- // behavior. The continuation byte check is included three times in the case
- // where all of the continuation bytes for a character exist in the same buffer.
- // It is also done this way as a slight performance increase instead of using a
- // loop.
- function utf8CheckExtraBytes(self, buf, p) {
- if ((buf[0] & 0xC0) !== 0x80) {
- self.lastNeed = 0;
- return '\ufffd';
- }
- if (self.lastNeed > 1 && buf.length > 1) {
- if ((buf[1] & 0xC0) !== 0x80) {
- self.lastNeed = 1;
- return '\ufffd';
- }
- if (self.lastNeed > 2 && buf.length > 2) {
- if ((buf[2] & 0xC0) !== 0x80) {
- self.lastNeed = 2;
- return '\ufffd';
- }
- }
- }
- }
- // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
- function utf8FillLast(buf) {
- var p = this.lastTotal - this.lastNeed;
- var r = utf8CheckExtraBytes(this, buf, p);
- if (r !== undefined) return r;
- if (this.lastNeed <= buf.length) {
- buf.copy(this.lastChar, p, 0, this.lastNeed);
- return this.lastChar.toString(this.encoding, 0, this.lastTotal);
- }
- buf.copy(this.lastChar, p, 0, buf.length);
- this.lastNeed -= buf.length;
- }
- // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
- // partial character, the character's bytes are buffered until the required
- // number of bytes are available.
- function utf8Text(buf, i) {
- var total = utf8CheckIncomplete(this, buf, i);
- if (!this.lastNeed) return buf.toString('utf8', i);
- this.lastTotal = total;
- var end = buf.length - (total - this.lastNeed);
- buf.copy(this.lastChar, 0, end);
- return buf.toString('utf8', i, end);
- }
- // For UTF-8, a replacement character is added when ending on a partial
- // character.
- function utf8End(buf) {
- var r = buf && buf.length ? this.write(buf) : '';
- if (this.lastNeed) return r + '\ufffd';
- return r;
- }
- // UTF-16LE typically needs two bytes per character, but even if we have an even
- // number of bytes available, we need to check if we end on a leading/high
- // surrogate. In that case, we need to wait for the next two bytes in order to
- // decode the last character properly.
- function utf16Text(buf, i) {
- if ((buf.length - i) % 2 === 0) {
- var r = buf.toString('utf16le', i);
- if (r) {
- var c = r.charCodeAt(r.length - 1);
- if (c >= 0xD800 && c <= 0xDBFF) {
- this.lastNeed = 2;
- this.lastTotal = 4;
- this.lastChar[0] = buf[buf.length - 2];
- this.lastChar[1] = buf[buf.length - 1];
- return r.slice(0, -1);
- }
- }
- return r;
- }
- this.lastNeed = 1;
- this.lastTotal = 2;
- this.lastChar[0] = buf[buf.length - 1];
- return buf.toString('utf16le', i, buf.length - 1);
- }
- // For UTF-16LE we do not explicitly append special replacement characters if we
- // end on a partial character, we simply let v8 handle that.
- function utf16End(buf) {
- var r = buf && buf.length ? this.write(buf) : '';
- if (this.lastNeed) {
- var end = this.lastTotal - this.lastNeed;
- return r + this.lastChar.toString('utf16le', 0, end);
- }
- return r;
- }
- function base64Text(buf, i) {
- var n = (buf.length - i) % 3;
- if (n === 0) return buf.toString('base64', i);
- this.lastNeed = 3 - n;
- this.lastTotal = 3;
- if (n === 1) {
- this.lastChar[0] = buf[buf.length - 1];
- } else {
- this.lastChar[0] = buf[buf.length - 2];
- this.lastChar[1] = buf[buf.length - 1];
- }
- return buf.toString('base64', i, buf.length - n);
- }
- function base64End(buf) {
- var r = buf && buf.length ? this.write(buf) : '';
- if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
- return r;
- }
- // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
- function simpleWrite(buf) {
- return buf.toString(this.encoding);
- }
- function simpleEnd(buf) {
- return buf && buf.length ? this.write(buf) : '';
- }
- },{"safe-buffer":326}],328:[function(require,module,exports){
- module.exports = require('./readable').PassThrough
- },{"./readable":329}],329:[function(require,module,exports){
- exports = module.exports = require('./lib/_stream_readable.js');
- exports.Stream = exports;
- exports.Readable = exports;
- exports.Writable = require('./lib/_stream_writable.js');
- exports.Duplex = require('./lib/_stream_duplex.js');
- exports.Transform = require('./lib/_stream_transform.js');
- exports.PassThrough = require('./lib/_stream_passthrough.js');
- },{"./lib/_stream_duplex.js":318,"./lib/_stream_passthrough.js":319,"./lib/_stream_readable.js":320,"./lib/_stream_transform.js":321,"./lib/_stream_writable.js":322}],330:[function(require,module,exports){
- module.exports = require('./readable').Transform
- },{"./readable":329}],331:[function(require,module,exports){
- module.exports = require('./lib/_stream_writable.js');
- },{"./lib/_stream_writable.js":322}],332:[function(require,module,exports){
- /**
- * Copyright (c) 2014-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- var runtime = (function (exports) {
- "use strict";
- var Op = Object.prototype;
- var hasOwn = Op.hasOwnProperty;
- var undefined; // More compressible than void 0.
- var $Symbol = typeof Symbol === "function" ? Symbol : {};
- var iteratorSymbol = $Symbol.iterator || "@@iterator";
- var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
- var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
- function wrap(innerFn, outerFn, self, tryLocsList) {
- // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
- var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
- var generator = Object.create(protoGenerator.prototype);
- var context = new Context(tryLocsList || []);
- // The ._invoke method unifies the implementations of the .next,
- // .throw, and .return methods.
- generator._invoke = makeInvokeMethod(innerFn, self, context);
- return generator;
- }
- exports.wrap = wrap;
- // Try/catch helper to minimize deoptimizations. Returns a completion
- // record like context.tryEntries[i].completion. This interface could
- // have been (and was previously) designed to take a closure to be
- // invoked without arguments, but in all the cases we care about we
- // already have an existing method we want to call, so there's no need
- // to create a new function object. We can even get away with assuming
- // the method takes exactly one argument, since that happens to be true
- // in every case, so we don't have to touch the arguments object. The
- // only additional allocation required is the completion record, which
- // has a stable shape and so hopefully should be cheap to allocate.
- function tryCatch(fn, obj, arg) {
- try {
- return { type: "normal", arg: fn.call(obj, arg) };
- } catch (err) {
- return { type: "throw", arg: err };
- }
- }
- var GenStateSuspendedStart = "suspendedStart";
- var GenStateSuspendedYield = "suspendedYield";
- var GenStateExecuting = "executing";
- var GenStateCompleted = "completed";
- // Returning this object from the innerFn has the same effect as
- // breaking out of the dispatch switch statement.
- var ContinueSentinel = {};
- // Dummy constructor functions that we use as the .constructor and
- // .constructor.prototype properties for functions that return Generator
- // objects. For full spec compliance, you may wish to configure your
- // minifier not to mangle the names of these two functions.
- function Generator() {}
- function GeneratorFunction() {}
- function GeneratorFunctionPrototype() {}
- // This is a polyfill for %IteratorPrototype% for environments that
- // don't natively support it.
- var IteratorPrototype = {};
- IteratorPrototype[iteratorSymbol] = function () {
- return this;
- };
- var getProto = Object.getPrototypeOf;
- var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
- if (NativeIteratorPrototype &&
- NativeIteratorPrototype !== Op &&
- hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
- // This environment has a native %IteratorPrototype%; use it instead
- // of the polyfill.
- IteratorPrototype = NativeIteratorPrototype;
- }
- var Gp = GeneratorFunctionPrototype.prototype =
- Generator.prototype = Object.create(IteratorPrototype);
- GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
- GeneratorFunctionPrototype.constructor = GeneratorFunction;
- GeneratorFunctionPrototype[toStringTagSymbol] =
- GeneratorFunction.displayName = "GeneratorFunction";
- // Helper for defining the .next, .throw, and .return methods of the
- // Iterator interface in terms of a single ._invoke method.
- function defineIteratorMethods(prototype) {
- ["next", "throw", "return"].forEach(function(method) {
- prototype[method] = function(arg) {
- return this._invoke(method, arg);
- };
- });
- }
- exports.isGeneratorFunction = function(genFun) {
- var ctor = typeof genFun === "function" && genFun.constructor;
- return ctor
- ? ctor === GeneratorFunction ||
- // For the native GeneratorFunction constructor, the best we can
- // do is to check its .name property.
- (ctor.displayName || ctor.name) === "GeneratorFunction"
- : false;
- };
- exports.mark = function(genFun) {
- if (Object.setPrototypeOf) {
- Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
- } else {
- genFun.__proto__ = GeneratorFunctionPrototype;
- if (!(toStringTagSymbol in genFun)) {
- genFun[toStringTagSymbol] = "GeneratorFunction";
- }
- }
- genFun.prototype = Object.create(Gp);
- return genFun;
- };
- // Within the body of any async function, `await x` is transformed to
- // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
- // `hasOwn.call(value, "__await")` to determine if the yielded value is
- // meant to be awaited.
- exports.awrap = function(arg) {
- return { __await: arg };
- };
- function AsyncIterator(generator) {
- function invoke(method, arg, resolve, reject) {
- var record = tryCatch(generator[method], generator, arg);
- if (record.type === "throw") {
- reject(record.arg);
- } else {
- var result = record.arg;
- var value = result.value;
- if (value &&
- typeof value === "object" &&
- hasOwn.call(value, "__await")) {
- return Promise.resolve(value.__await).then(function(value) {
- invoke("next", value, resolve, reject);
- }, function(err) {
- invoke("throw", err, resolve, reject);
- });
- }
- return Promise.resolve(value).then(function(unwrapped) {
- // When a yielded Promise is resolved, its final value becomes
- // the .value of the Promise<{value,done}> result for the
- // current iteration.
- result.value = unwrapped;
- resolve(result);
- }, function(error) {
- // If a rejected Promise was yielded, throw the rejection back
- // into the async generator function so it can be handled there.
- return invoke("throw", error, resolve, reject);
- });
- }
- }
- var previousPromise;
- function enqueue(method, arg) {
- function callInvokeWithMethodAndArg() {
- return new Promise(function(resolve, reject) {
- invoke(method, arg, resolve, reject);
- });
- }
- return previousPromise =
- // If enqueue has been called before, then we want to wait until
- // all previous Promises have been resolved before calling invoke,
- // so that results are always delivered in the correct order. If
- // enqueue has not been called before, then it is important to
- // call invoke immediately, without waiting on a callback to fire,
- // so that the async generator function has the opportunity to do
- // any necessary setup in a predictable way. This predictability
- // is why the Promise constructor synchronously invokes its
- // executor callback, and why async functions synchronously
- // execute code before the first await. Since we implement simple
- // async functions in terms of async generators, it is especially
- // important to get this right, even though it requires care.
- previousPromise ? previousPromise.then(
- callInvokeWithMethodAndArg,
- // Avoid propagating failures to Promises returned by later
- // invocations of the iterator.
- callInvokeWithMethodAndArg
- ) : callInvokeWithMethodAndArg();
- }
- // Define the unified helper method that is used to implement .next,
- // .throw, and .return (see defineIteratorMethods).
- this._invoke = enqueue;
- }
- defineIteratorMethods(AsyncIterator.prototype);
- AsyncIterator.prototype[asyncIteratorSymbol] = function () {
- return this;
- };
- exports.AsyncIterator = AsyncIterator;
- // Note that simple async functions are implemented on top of
- // AsyncIterator objects; they just return a Promise for the value of
- // the final result produced by the iterator.
- exports.async = function(innerFn, outerFn, self, tryLocsList) {
- var iter = new AsyncIterator(
- wrap(innerFn, outerFn, self, tryLocsList)
- );
- return exports.isGeneratorFunction(outerFn)
- ? iter // If outerFn is a generator, return the full iterator.
- : iter.next().then(function(result) {
- return result.done ? result.value : iter.next();
- });
- };
- function makeInvokeMethod(innerFn, self, context) {
- var state = GenStateSuspendedStart;
- return function invoke(method, arg) {
- if (state === GenStateExecuting) {
- throw new Error("Generator is already running");
- }
- if (state === GenStateCompleted) {
- if (method === "throw") {
- throw arg;
- }
- // Be forgiving, per 25.3.3.3.3 of the spec:
- // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
- return doneResult();
- }
- context.method = method;
- context.arg = arg;
- while (true) {
- var delegate = context.delegate;
- if (delegate) {
- var delegateResult = maybeInvokeDelegate(delegate, context);
- if (delegateResult) {
- if (delegateResult === ContinueSentinel) continue;
- return delegateResult;
- }
- }
- if (context.method === "next") {
- // Setting context._sent for legacy support of Babel's
- // function.sent implementation.
- context.sent = context._sent = context.arg;
- } else if (context.method === "throw") {
- if (state === GenStateSuspendedStart) {
- state = GenStateCompleted;
- throw context.arg;
- }
- context.dispatchException(context.arg);
- } else if (context.method === "return") {
- context.abrupt("return", context.arg);
- }
- state = GenStateExecuting;
- var record = tryCatch(innerFn, self, context);
- if (record.type === "normal") {
- // If an exception is thrown from innerFn, we leave state ===
- // GenStateExecuting and loop back for another invocation.
- state = context.done
- ? GenStateCompleted
- : GenStateSuspendedYield;
- if (record.arg === ContinueSentinel) {
- continue;
- }
- return {
- value: record.arg,
- done: context.done
- };
- } else if (record.type === "throw") {
- state = GenStateCompleted;
- // Dispatch the exception by looping back around to the
- // context.dispatchException(context.arg) call above.
- context.method = "throw";
- context.arg = record.arg;
- }
- }
- };
- }
- // Call delegate.iterator[context.method](context.arg) and handle the
- // result, either by returning a { value, done } result from the
- // delegate iterator, or by modifying context.method and context.arg,
- // setting context.delegate to null, and returning the ContinueSentinel.
- function maybeInvokeDelegate(delegate, context) {
- var method = delegate.iterator[context.method];
- if (method === undefined) {
- // A .throw or .return when the delegate iterator has no .throw
- // method always terminates the yield* loop.
- context.delegate = null;
- if (context.method === "throw") {
- // Note: ["return"] must be used for ES3 parsing compatibility.
- if (delegate.iterator["return"]) {
- // If the delegate iterator has a return method, give it a
- // chance to clean up.
- context.method = "return";
- context.arg = undefined;
- maybeInvokeDelegate(delegate, context);
- if (context.method === "throw") {
- // If maybeInvokeDelegate(context) changed context.method from
- // "return" to "throw", let that override the TypeError below.
- return ContinueSentinel;
- }
- }
- context.method = "throw";
- context.arg = new TypeError(
- "The iterator does not provide a 'throw' method");
- }
- return ContinueSentinel;
- }
- var record = tryCatch(method, delegate.iterator, context.arg);
- if (record.type === "throw") {
- context.method = "throw";
- context.arg = record.arg;
- context.delegate = null;
- return ContinueSentinel;
- }
- var info = record.arg;
- if (! info) {
- context.method = "throw";
- context.arg = new TypeError("iterator result is not an object");
- context.delegate = null;
- return ContinueSentinel;
- }
- if (info.done) {
- // Assign the result of the finished delegate to the temporary
- // variable specified by delegate.resultName (see delegateYield).
- context[delegate.resultName] = info.value;
- // Resume execution at the desired location (see delegateYield).
- context.next = delegate.nextLoc;
- // If context.method was "throw" but the delegate handled the
- // exception, let the outer generator proceed normally. If
- // context.method was "next", forget context.arg since it has been
- // "consumed" by the delegate iterator. If context.method was
- // "return", allow the original .return call to continue in the
- // outer generator.
- if (context.method !== "return") {
- context.method = "next";
- context.arg = undefined;
- }
- } else {
- // Re-yield the result returned by the delegate method.
- return info;
- }
- // The delegate iterator is finished, so forget it and continue with
- // the outer generator.
- context.delegate = null;
- return ContinueSentinel;
- }
- // Define Generator.prototype.{next,throw,return} in terms of the
- // unified ._invoke helper method.
- defineIteratorMethods(Gp);
- Gp[toStringTagSymbol] = "Generator";
- // A Generator should always return itself as the iterator object when the
- // @@iterator function is called on it. Some browsers' implementations of the
- // iterator prototype chain incorrectly implement this, causing the Generator
- // object to not be returned from this call. This ensures that doesn't happen.
- // See https://github.com/facebook/regenerator/issues/274 for more details.
- Gp[iteratorSymbol] = function() {
- return this;
- };
- Gp.toString = function() {
- return "[object Generator]";
- };
- function pushTryEntry(locs) {
- var entry = { tryLoc: locs[0] };
- if (1 in locs) {
- entry.catchLoc = locs[1];
- }
- if (2 in locs) {
- entry.finallyLoc = locs[2];
- entry.afterLoc = locs[3];
- }
- this.tryEntries.push(entry);
- }
- function resetTryEntry(entry) {
- var record = entry.completion || {};
- record.type = "normal";
- delete record.arg;
- entry.completion = record;
- }
- function Context(tryLocsList) {
- // The root entry object (effectively a try statement without a catch
- // or a finally block) gives us a place to store values thrown from
- // locations where there is no enclosing try statement.
- this.tryEntries = [{ tryLoc: "root" }];
- tryLocsList.forEach(pushTryEntry, this);
- this.reset(true);
- }
- exports.keys = function(object) {
- var keys = [];
- for (var key in object) {
- keys.push(key);
- }
- keys.reverse();
- // Rather than returning an object with a next method, we keep
- // things simple and return the next function itself.
- return function next() {
- while (keys.length) {
- var key = keys.pop();
- if (key in object) {
- next.value = key;
- next.done = false;
- return next;
- }
- }
- // To avoid creating an additional object, we just hang the .value
- // and .done properties off the next function object itself. This
- // also ensures that the minifier will not anonymize the function.
- next.done = true;
- return next;
- };
- };
- function values(iterable) {
- if (iterable) {
- var iteratorMethod = iterable[iteratorSymbol];
- if (iteratorMethod) {
- return iteratorMethod.call(iterable);
- }
- if (typeof iterable.next === "function") {
- return iterable;
- }
- if (!isNaN(iterable.length)) {
- var i = -1, next = function next() {
- while (++i < iterable.length) {
- if (hasOwn.call(iterable, i)) {
- next.value = iterable[i];
- next.done = false;
- return next;
- }
- }
- next.value = undefined;
- next.done = true;
- return next;
- };
- return next.next = next;
- }
- }
- // Return an iterator with no values.
- return { next: doneResult };
- }
- exports.values = values;
- function doneResult() {
- return { value: undefined, done: true };
- }
- Context.prototype = {
- constructor: Context,
- reset: function(skipTempReset) {
- this.prev = 0;
- this.next = 0;
- // Resetting context._sent for legacy support of Babel's
- // function.sent implementation.
- this.sent = this._sent = undefined;
- this.done = false;
- this.delegate = null;
- this.method = "next";
- this.arg = undefined;
- this.tryEntries.forEach(resetTryEntry);
- if (!skipTempReset) {
- for (var name in this) {
- // Not sure about the optimal order of these conditions:
- if (name.charAt(0) === "t" &&
- hasOwn.call(this, name) &&
- !isNaN(+name.slice(1))) {
- this[name] = undefined;
- }
- }
- }
- },
- stop: function() {
- this.done = true;
- var rootEntry = this.tryEntries[0];
- var rootRecord = rootEntry.completion;
- if (rootRecord.type === "throw") {
- throw rootRecord.arg;
- }
- return this.rval;
- },
- dispatchException: function(exception) {
- if (this.done) {
- throw exception;
- }
- var context = this;
- function handle(loc, caught) {
- record.type = "throw";
- record.arg = exception;
- context.next = loc;
- if (caught) {
- // If the dispatched exception was caught by a catch block,
- // then let that catch block handle the exception normally.
- context.method = "next";
- context.arg = undefined;
- }
- return !! caught;
- }
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- var record = entry.completion;
- if (entry.tryLoc === "root") {
- // Exception thrown outside of any try block that could handle
- // it, so set the completion value of the entire function to
- // throw the exception.
- return handle("end");
- }
- if (entry.tryLoc <= this.prev) {
- var hasCatch = hasOwn.call(entry, "catchLoc");
- var hasFinally = hasOwn.call(entry, "finallyLoc");
- if (hasCatch && hasFinally) {
- if (this.prev < entry.catchLoc) {
- return handle(entry.catchLoc, true);
- } else if (this.prev < entry.finallyLoc) {
- return handle(entry.finallyLoc);
- }
- } else if (hasCatch) {
- if (this.prev < entry.catchLoc) {
- return handle(entry.catchLoc, true);
- }
- } else if (hasFinally) {
- if (this.prev < entry.finallyLoc) {
- return handle(entry.finallyLoc);
- }
- } else {
- throw new Error("try statement without catch or finally");
- }
- }
- }
- },
- abrupt: function(type, arg) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.tryLoc <= this.prev &&
- hasOwn.call(entry, "finallyLoc") &&
- this.prev < entry.finallyLoc) {
- var finallyEntry = entry;
- break;
- }
- }
- if (finallyEntry &&
- (type === "break" ||
- type === "continue") &&
- finallyEntry.tryLoc <= arg &&
- arg <= finallyEntry.finallyLoc) {
- // Ignore the finally entry if control is not jumping to a
- // location outside the try/catch block.
- finallyEntry = null;
- }
- var record = finallyEntry ? finallyEntry.completion : {};
- record.type = type;
- record.arg = arg;
- if (finallyEntry) {
- this.method = "next";
- this.next = finallyEntry.finallyLoc;
- return ContinueSentinel;
- }
- return this.complete(record);
- },
- complete: function(record, afterLoc) {
- if (record.type === "throw") {
- throw record.arg;
- }
- if (record.type === "break" ||
- record.type === "continue") {
- this.next = record.arg;
- } else if (record.type === "return") {
- this.rval = this.arg = record.arg;
- this.method = "return";
- this.next = "end";
- } else if (record.type === "normal" && afterLoc) {
- this.next = afterLoc;
- }
- return ContinueSentinel;
- },
- finish: function(finallyLoc) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.finallyLoc === finallyLoc) {
- this.complete(entry.completion, entry.afterLoc);
- resetTryEntry(entry);
- return ContinueSentinel;
- }
- }
- },
- "catch": function(tryLoc) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.tryLoc === tryLoc) {
- var record = entry.completion;
- if (record.type === "throw") {
- var thrown = record.arg;
- resetTryEntry(entry);
- }
- return thrown;
- }
- }
- // The context.catch method must only be called with a location
- // argument that corresponds to a known catch block.
- throw new Error("illegal catch attempt");
- },
- delegateYield: function(iterable, resultName, nextLoc) {
- this.delegate = {
- iterator: values(iterable),
- resultName: resultName,
- nextLoc: nextLoc
- };
- if (this.method === "next") {
- // Deliberately forget the last sent value so that we don't
- // accidentally pass it on to the delegate.
- this.arg = undefined;
- }
- return ContinueSentinel;
- }
- };
- // Regardless of whether this script is executing as a CommonJS module
- // or not, return the runtime object so that we can declare the variable
- // regeneratorRuntime in the outer scope, which allows this module to be
- // injected easily by `bin/regenerator --include-runtime script.js`.
- return exports;
- }(
- // If this script is executing as a CommonJS module, use module.exports
- // as the regeneratorRuntime namespace. Otherwise create a new empty
- // object. Either way, the resulting object will be used to initialize
- // the regeneratorRuntime variable at the top of this file.
- typeof module === "object" ? module.exports : {}
- ));
- try {
- regeneratorRuntime = runtime;
- } catch (accidentalStrictMode) {
- // This module should not be running in strict mode, so the above
- // assignment should always work unless something is misconfigured. Just
- // in case runtime.js accidentally runs in strict mode, we can escape
- // strict mode using a global Function call. This could conceivably fail
- // if a Content Security Policy forbids using Function, but in that case
- // the proper solution is to fix the accidental strict mode problem. If
- // you've misconfigured your bundler to force strict mode and applied a
- // CSP to forbid Function, and you're not willing to fix either of those
- // problems, please detail your unique predicament in a GitHub issue.
- Function("r", "regeneratorRuntime = r")(runtime);
- }
- },{}],333:[function(require,module,exports){
- /* eslint-disable node/no-deprecated-api */
- var buffer = require('buffer')
- var Buffer = buffer.Buffer
- // alternative to using Object.keys for old browsers
- function copyProps (src, dst) {
- for (var key in src) {
- dst[key] = src[key]
- }
- }
- if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
- module.exports = buffer
- } else {
- // Copy properties from require('buffer')
- copyProps(buffer, exports)
- exports.Buffer = SafeBuffer
- }
- function SafeBuffer (arg, encodingOrOffset, length) {
- return Buffer(arg, encodingOrOffset, length)
- }
- SafeBuffer.prototype = Object.create(Buffer.prototype)
- // Copy static methods from Buffer
- copyProps(Buffer, SafeBuffer)
- SafeBuffer.from = function (arg, encodingOrOffset, length) {
- if (typeof arg === 'number') {
- throw new TypeError('Argument must not be a number')
- }
- return Buffer(arg, encodingOrOffset, length)
- }
- SafeBuffer.alloc = function (size, fill, encoding) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- var buf = Buffer(size)
- if (fill !== undefined) {
- if (typeof encoding === 'string') {
- buf.fill(fill, encoding)
- } else {
- buf.fill(fill)
- }
- } else {
- buf.fill(0)
- }
- return buf
- }
- SafeBuffer.allocUnsafe = function (size) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- return Buffer(size)
- }
- SafeBuffer.allocUnsafeSlow = function (size) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- return buffer.SlowBuffer(size)
- }
- },{"buffer":47}],334:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- module.exports = Stream;
- var EE = require('events').EventEmitter;
- var inherits = require('inherits');
- inherits(Stream, EE);
- Stream.Readable = require('readable-stream/readable.js');
- Stream.Writable = require('readable-stream/writable.js');
- Stream.Duplex = require('readable-stream/duplex.js');
- Stream.Transform = require('readable-stream/transform.js');
- Stream.PassThrough = require('readable-stream/passthrough.js');
- // Backwards-compat with node 0.4.x
- Stream.Stream = Stream;
- // old-style streams. Note that the pipe method (the only relevant
- // part of this class) is overridden in the Readable class.
- function Stream() {
- EE.call(this);
- }
- Stream.prototype.pipe = function(dest, options) {
- var source = this;
- function ondata(chunk) {
- if (dest.writable) {
- if (false === dest.write(chunk) && source.pause) {
- source.pause();
- }
- }
- }
- source.on('data', ondata);
- function ondrain() {
- if (source.readable && source.resume) {
- source.resume();
- }
- }
- dest.on('drain', ondrain);
- // If the 'end' option is not supplied, dest.end() will be called when
- // source gets the 'end' or 'close' events. Only dest.end() once.
- if (!dest._isStdio && (!options || options.end !== false)) {
- source.on('end', onend);
- source.on('close', onclose);
- }
- var didOnEnd = false;
- function onend() {
- if (didOnEnd) return;
- didOnEnd = true;
- dest.end();
- }
- function onclose() {
- if (didOnEnd) return;
- didOnEnd = true;
- if (typeof dest.destroy === 'function') dest.destroy();
- }
- // don't leave dangling pipes when there are errors.
- function onerror(er) {
- cleanup();
- if (EE.listenerCount(this, 'error') === 0) {
- throw er; // Unhandled stream error in pipe.
- }
- }
- source.on('error', onerror);
- dest.on('error', onerror);
- // remove all the event listeners that were added.
- function cleanup() {
- source.removeListener('data', ondata);
- dest.removeListener('drain', ondrain);
- source.removeListener('end', onend);
- source.removeListener('close', onclose);
- source.removeListener('error', onerror);
- dest.removeListener('error', onerror);
- source.removeListener('end', cleanup);
- source.removeListener('close', cleanup);
- dest.removeListener('close', cleanup);
- }
- source.on('end', cleanup);
- source.on('close', cleanup);
- dest.on('close', cleanup);
- dest.emit('pipe', source);
- // Allow for unix-like usage: A.pipe(B).pipe(C)
- return dest;
- };
- },{"events":239,"inherits":254,"readable-stream/duplex.js":317,"readable-stream/passthrough.js":328,"readable-stream/readable.js":329,"readable-stream/transform.js":330,"readable-stream/writable.js":331}],335:[function(require,module,exports){
- (function (global){
- var ClientRequest = require('./lib/request')
- var response = require('./lib/response')
- var extend = require('xtend')
- var statusCodes = require('builtin-status-codes')
- var url = require('url')
- var http = exports
- http.request = function (opts, cb) {
- if (typeof opts === 'string')
- opts = url.parse(opts)
- else
- opts = extend(opts)
- // Normally, the page is loaded from http or https, so not specifying a protocol
- // will result in a (valid) protocol-relative url. However, this won't work if
- // the protocol is something else, like 'file:'
- var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
- var protocol = opts.protocol || defaultProtocol
- var host = opts.hostname || opts.host
- var port = opts.port
- var path = opts.path || '/'
- // Necessary for IPv6 addresses
- if (host && host.indexOf(':') !== -1)
- host = '[' + host + ']'
- // This may be a relative url. The browser should always be able to interpret it correctly.
- opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
- opts.method = (opts.method || 'GET').toUpperCase()
- opts.headers = opts.headers || {}
- // Also valid opts.auth, opts.mode
- var req = new ClientRequest(opts)
- if (cb)
- req.on('response', cb)
- return req
- }
- http.get = function get (opts, cb) {
- var req = http.request(opts, cb)
- req.end()
- return req
- }
- http.ClientRequest = ClientRequest
- http.IncomingMessage = response.IncomingMessage
- http.Agent = function () {}
- http.Agent.defaultMaxSockets = 4
- http.globalAgent = new http.Agent()
- http.STATUS_CODES = statusCodes
- http.METHODS = [
- 'CHECKOUT',
- 'CONNECT',
- 'COPY',
- 'DELETE',
- 'GET',
- 'HEAD',
- 'LOCK',
- 'M-SEARCH',
- 'MERGE',
- 'MKACTIVITY',
- 'MKCOL',
- 'MOVE',
- 'NOTIFY',
- 'OPTIONS',
- 'PATCH',
- 'POST',
- 'PROPFIND',
- 'PROPPATCH',
- 'PURGE',
- 'PUT',
- 'REPORT',
- 'SEARCH',
- 'SUBSCRIBE',
- 'TRACE',
- 'UNLOCK',
- 'UNSUBSCRIBE'
- ]
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./lib/request":337,"./lib/response":338,"builtin-status-codes":49,"url":359,"xtend":368}],336:[function(require,module,exports){
- (function (global){
- exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
- exports.writableStream = isFunction(global.WritableStream)
- exports.abortController = isFunction(global.AbortController)
- // The xhr request to example.com may violate some restrictive CSP configurations,
- // so if we're running in a browser that supports `fetch`, avoid calling getXHR()
- // and assume support for certain features below.
- var xhr
- function getXHR () {
- // Cache the xhr value
- if (xhr !== undefined) return xhr
- if (global.XMLHttpRequest) {
- xhr = new global.XMLHttpRequest()
- // If XDomainRequest is available (ie only, where xhr might not work
- // cross domain), use the page location. Otherwise use example.com
- // Note: this doesn't actually make an http request.
- try {
- xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
- } catch(e) {
- xhr = null
- }
- } else {
- // Service workers don't have XHR
- xhr = null
- }
- return xhr
- }
- function checkTypeSupport (type) {
- var xhr = getXHR()
- if (!xhr) return false
- try {
- xhr.responseType = type
- return xhr.responseType === type
- } catch (e) {}
- return false
- }
- // If fetch is supported, then arraybuffer will be supported too. Skip calling
- // checkTypeSupport(), since that calls getXHR().
- exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer')
- // These next two tests unavoidably show warnings in Chrome. Since fetch will always
- // be used if it's available, just return false for these to avoid the warnings.
- exports.msstream = !exports.fetch && checkTypeSupport('ms-stream')
- exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer')
- // If fetch is supported, then overrideMimeType will be supported too. Skip calling
- // getXHR().
- exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
- function isFunction (value) {
- return typeof value === 'function'
- }
- xhr = null // Help gc
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],337:[function(require,module,exports){
- (function (process,global,Buffer){
- var capability = require('./capability')
- var inherits = require('inherits')
- var response = require('./response')
- var stream = require('readable-stream')
- var IncomingMessage = response.IncomingMessage
- var rStates = response.readyStates
- function decideMode (preferBinary, useFetch) {
- if (capability.fetch && useFetch) {
- return 'fetch'
- } else if (capability.mozchunkedarraybuffer) {
- return 'moz-chunked-arraybuffer'
- } else if (capability.msstream) {
- return 'ms-stream'
- } else if (capability.arraybuffer && preferBinary) {
- return 'arraybuffer'
- } else {
- return 'text'
- }
- }
- var ClientRequest = module.exports = function (opts) {
- var self = this
- stream.Writable.call(self)
- self._opts = opts
- self._body = []
- self._headers = {}
- if (opts.auth)
- self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64'))
- Object.keys(opts.headers).forEach(function (name) {
- self.setHeader(name, opts.headers[name])
- })
- var preferBinary
- var useFetch = true
- if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
- // If the use of XHR should be preferred. Not typically needed.
- useFetch = false
- preferBinary = true
- } else if (opts.mode === 'prefer-streaming') {
- // If streaming is a high priority but binary compatibility and
- // the accuracy of the 'content-type' header aren't
- preferBinary = false
- } else if (opts.mode === 'allow-wrong-content-type') {
- // If streaming is more important than preserving the 'content-type' header
- preferBinary = !capability.overrideMimeType
- } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
- // Use binary if text streaming may corrupt data or the content-type header, or for speed
- preferBinary = true
- } else {
- throw new Error('Invalid value for opts.mode')
- }
- self._mode = decideMode(preferBinary, useFetch)
- self._fetchTimer = null
- self.on('finish', function () {
- self._onFinish()
- })
- }
- inherits(ClientRequest, stream.Writable)
- ClientRequest.prototype.setHeader = function (name, value) {
- var self = this
- var lowerName = name.toLowerCase()
- // This check is not necessary, but it prevents warnings from browsers about setting unsafe
- // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
- // http-browserify did it, so I will too.
- if (unsafeHeaders.indexOf(lowerName) !== -1)
- return
- self._headers[lowerName] = {
- name: name,
- value: value
- }
- }
- ClientRequest.prototype.getHeader = function (name) {
- var header = this._headers[name.toLowerCase()]
- if (header)
- return header.value
- return null
- }
- ClientRequest.prototype.removeHeader = function (name) {
- var self = this
- delete self._headers[name.toLowerCase()]
- }
- ClientRequest.prototype._onFinish = function () {
- var self = this
- if (self._destroyed)
- return
- var opts = self._opts
- var headersObj = self._headers
- var body = null
- if (opts.method !== 'GET' && opts.method !== 'HEAD') {
- body = new Blob(self._body, {
- type: (headersObj['content-type'] || {}).value || ''
- });
- }
- // create flattened list of headers
- var headersList = []
- Object.keys(headersObj).forEach(function (keyName) {
- var name = headersObj[keyName].name
- var value = headersObj[keyName].value
- if (Array.isArray(value)) {
- value.forEach(function (v) {
- headersList.push([name, v])
- })
- } else {
- headersList.push([name, value])
- }
- })
- if (self._mode === 'fetch') {
- var signal = null
- var fetchTimer = null
- if (capability.abortController) {
- var controller = new AbortController()
- signal = controller.signal
- self._fetchAbortController = controller
- if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
- self._fetchTimer = global.setTimeout(function () {
- self.emit('requestTimeout')
- if (self._fetchAbortController)
- self._fetchAbortController.abort()
- }, opts.requestTimeout)
- }
- }
- global.fetch(self._opts.url, {
- method: self._opts.method,
- headers: headersList,
- body: body || undefined,
- mode: 'cors',
- credentials: opts.withCredentials ? 'include' : 'same-origin',
- signal: signal
- }).then(function (response) {
- self._fetchResponse = response
- self._connect()
- }, function (reason) {
- global.clearTimeout(self._fetchTimer)
- if (!self._destroyed)
- self.emit('error', reason)
- })
- } else {
- var xhr = self._xhr = new global.XMLHttpRequest()
- try {
- xhr.open(self._opts.method, self._opts.url, true)
- } catch (err) {
- process.nextTick(function () {
- self.emit('error', err)
- })
- return
- }
- // Can't set responseType on really old browsers
- if ('responseType' in xhr)
- xhr.responseType = self._mode
- if ('withCredentials' in xhr)
- xhr.withCredentials = !!opts.withCredentials
- if (self._mode === 'text' && 'overrideMimeType' in xhr)
- xhr.overrideMimeType('text/plain; charset=x-user-defined')
- if ('requestTimeout' in opts) {
- xhr.timeout = opts.requestTimeout
- xhr.ontimeout = function () {
- self.emit('requestTimeout')
- }
- }
- headersList.forEach(function (header) {
- xhr.setRequestHeader(header[0], header[1])
- })
- self._response = null
- xhr.onreadystatechange = function () {
- switch (xhr.readyState) {
- case rStates.LOADING:
- case rStates.DONE:
- self._onXHRProgress()
- break
- }
- }
- // Necessary for streaming in Firefox, since xhr.response is ONLY defined
- // in onprogress, not in onreadystatechange with xhr.readyState = 3
- if (self._mode === 'moz-chunked-arraybuffer') {
- xhr.onprogress = function () {
- self._onXHRProgress()
- }
- }
- xhr.onerror = function () {
- if (self._destroyed)
- return
- self.emit('error', new Error('XHR error'))
- }
- try {
- xhr.send(body)
- } catch (err) {
- process.nextTick(function () {
- self.emit('error', err)
- })
- return
- }
- }
- }
- /**
- * Checks if xhr.status is readable and non-zero, indicating no error.
- * Even though the spec says it should be available in readyState 3,
- * accessing it throws an exception in IE8
- */
- function statusValid (xhr) {
- try {
- var status = xhr.status
- return (status !== null && status !== 0)
- } catch (e) {
- return false
- }
- }
- ClientRequest.prototype._onXHRProgress = function () {
- var self = this
- if (!statusValid(self._xhr) || self._destroyed)
- return
- if (!self._response)
- self._connect()
- self._response._onXHRProgress()
- }
- ClientRequest.prototype._connect = function () {
- var self = this
- if (self._destroyed)
- return
- self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer)
- self._response.on('error', function(err) {
- self.emit('error', err)
- })
- self.emit('response', self._response)
- }
- ClientRequest.prototype._write = function (chunk, encoding, cb) {
- var self = this
- self._body.push(chunk)
- cb()
- }
- ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
- var self = this
- self._destroyed = true
- global.clearTimeout(self._fetchTimer)
- if (self._response)
- self._response._destroyed = true
- if (self._xhr)
- self._xhr.abort()
- else if (self._fetchAbortController)
- self._fetchAbortController.abort()
- }
- ClientRequest.prototype.end = function (data, encoding, cb) {
- var self = this
- if (typeof data === 'function') {
- cb = data
- data = undefined
- }
- stream.Writable.prototype.end.call(self, data, encoding, cb)
- }
- ClientRequest.prototype.flushHeaders = function () {}
- ClientRequest.prototype.setTimeout = function () {}
- ClientRequest.prototype.setNoDelay = function () {}
- ClientRequest.prototype.setSocketKeepAlive = function () {}
- // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
- var unsafeHeaders = [
- 'accept-charset',
- 'accept-encoding',
- 'access-control-request-headers',
- 'access-control-request-method',
- 'connection',
- 'content-length',
- 'cookie',
- 'cookie2',
- 'date',
- 'dnt',
- 'expect',
- 'host',
- 'keep-alive',
- 'origin',
- 'referer',
- 'te',
- 'trailer',
- 'transfer-encoding',
- 'upgrade',
- 'via'
- ]
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
- },{"./capability":336,"./response":338,"_process":312,"buffer":47,"inherits":254,"readable-stream":353}],338:[function(require,module,exports){
- (function (process,global,Buffer){
- var capability = require('./capability')
- var inherits = require('inherits')
- var stream = require('readable-stream')
- var rStates = exports.readyStates = {
- UNSENT: 0,
- OPENED: 1,
- HEADERS_RECEIVED: 2,
- LOADING: 3,
- DONE: 4
- }
- var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) {
- var self = this
- stream.Readable.call(self)
- self._mode = mode
- self.headers = {}
- self.rawHeaders = []
- self.trailers = {}
- self.rawTrailers = []
- // Fake the 'close' event, but only once 'end' fires
- self.on('end', function () {
- // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
- process.nextTick(function () {
- self.emit('close')
- })
- })
- if (mode === 'fetch') {
- self._fetchResponse = response
- self.url = response.url
- self.statusCode = response.status
- self.statusMessage = response.statusText
-
- response.headers.forEach(function (header, key){
- self.headers[key.toLowerCase()] = header
- self.rawHeaders.push(key, header)
- })
- if (capability.writableStream) {
- var writable = new WritableStream({
- write: function (chunk) {
- return new Promise(function (resolve, reject) {
- if (self._destroyed) {
- reject()
- } else if(self.push(Buffer.from(chunk))) {
- resolve()
- } else {
- self._resumeFetch = resolve
- }
- })
- },
- close: function () {
- global.clearTimeout(fetchTimer)
- if (!self._destroyed)
- self.push(null)
- },
- abort: function (err) {
- if (!self._destroyed)
- self.emit('error', err)
- }
- })
- try {
- response.body.pipeTo(writable).catch(function (err) {
- global.clearTimeout(fetchTimer)
- if (!self._destroyed)
- self.emit('error', err)
- })
- return
- } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
- }
- // fallback for when writableStream or pipeTo aren't available
- var reader = response.body.getReader()
- function read () {
- reader.read().then(function (result) {
- if (self._destroyed)
- return
- if (result.done) {
- global.clearTimeout(fetchTimer)
- self.push(null)
- return
- }
- self.push(Buffer.from(result.value))
- read()
- }).catch(function (err) {
- global.clearTimeout(fetchTimer)
- if (!self._destroyed)
- self.emit('error', err)
- })
- }
- read()
- } else {
- self._xhr = xhr
- self._pos = 0
- self.url = xhr.responseURL
- self.statusCode = xhr.status
- self.statusMessage = xhr.statusText
- var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
- headers.forEach(function (header) {
- var matches = header.match(/^([^:]+):\s*(.*)/)
- if (matches) {
- var key = matches[1].toLowerCase()
- if (key === 'set-cookie') {
- if (self.headers[key] === undefined) {
- self.headers[key] = []
- }
- self.headers[key].push(matches[2])
- } else if (self.headers[key] !== undefined) {
- self.headers[key] += ', ' + matches[2]
- } else {
- self.headers[key] = matches[2]
- }
- self.rawHeaders.push(matches[1], matches[2])
- }
- })
- self._charset = 'x-user-defined'
- if (!capability.overrideMimeType) {
- var mimeType = self.rawHeaders['mime-type']
- if (mimeType) {
- var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
- if (charsetMatch) {
- self._charset = charsetMatch[1].toLowerCase()
- }
- }
- if (!self._charset)
- self._charset = 'utf-8' // best guess
- }
- }
- }
- inherits(IncomingMessage, stream.Readable)
- IncomingMessage.prototype._read = function () {
- var self = this
- var resolve = self._resumeFetch
- if (resolve) {
- self._resumeFetch = null
- resolve()
- }
- }
- IncomingMessage.prototype._onXHRProgress = function () {
- var self = this
- var xhr = self._xhr
- var response = null
- switch (self._mode) {
- case 'text':
- response = xhr.responseText
- if (response.length > self._pos) {
- var newData = response.substr(self._pos)
- if (self._charset === 'x-user-defined') {
- var buffer = Buffer.alloc(newData.length)
- for (var i = 0; i < newData.length; i++)
- buffer[i] = newData.charCodeAt(i) & 0xff
- self.push(buffer)
- } else {
- self.push(newData, self._charset)
- }
- self._pos = response.length
- }
- break
- case 'arraybuffer':
- if (xhr.readyState !== rStates.DONE || !xhr.response)
- break
- response = xhr.response
- self.push(Buffer.from(new Uint8Array(response)))
- break
- case 'moz-chunked-arraybuffer': // take whole
- response = xhr.response
- if (xhr.readyState !== rStates.LOADING || !response)
- break
- self.push(Buffer.from(new Uint8Array(response)))
- break
- case 'ms-stream':
- response = xhr.response
- if (xhr.readyState !== rStates.LOADING)
- break
- var reader = new global.MSStreamReader()
- reader.onprogress = function () {
- if (reader.result.byteLength > self._pos) {
- self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos))))
- self._pos = reader.result.byteLength
- }
- }
- reader.onload = function () {
- self.push(null)
- }
- // reader.onerror = ??? // TODO: this
- reader.readAsArrayBuffer(response)
- break
- }
- // The ms-stream case handles end separately in reader.onload()
- if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
- self.push(null)
- }
- }
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
- },{"./capability":336,"_process":312,"buffer":47,"inherits":254,"readable-stream":353}],339:[function(require,module,exports){
- 'use strict';
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var codes = {};
- function createErrorType(code, message, Base) {
- if (!Base) {
- Base = Error;
- }
- function getMessage(arg1, arg2, arg3) {
- if (typeof message === 'string') {
- return message;
- } else {
- return message(arg1, arg2, arg3);
- }
- }
- var NodeError =
- /*#__PURE__*/
- function (_Base) {
- _inheritsLoose(NodeError, _Base);
- function NodeError(arg1, arg2, arg3) {
- return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
- }
- return NodeError;
- }(Base);
- NodeError.prototype.name = Base.name;
- NodeError.prototype.code = code;
- codes[code] = NodeError;
- } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
- function oneOf(expected, thing) {
- if (Array.isArray(expected)) {
- var len = expected.length;
- expected = expected.map(function (i) {
- return String(i);
- });
- if (len > 2) {
- return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
- } else if (len === 2) {
- return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
- } else {
- return "of ".concat(thing, " ").concat(expected[0]);
- }
- } else {
- return "of ".concat(thing, " ").concat(String(expected));
- }
- } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
- function startsWith(str, search, pos) {
- return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
- } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
- function endsWith(str, search, this_len) {
- if (this_len === undefined || this_len > str.length) {
- this_len = str.length;
- }
- return str.substring(this_len - search.length, this_len) === search;
- } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
- function includes(str, search, start) {
- if (typeof start !== 'number') {
- start = 0;
- }
- if (start + search.length > str.length) {
- return false;
- } else {
- return str.indexOf(search, start) !== -1;
- }
- }
- createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
- return 'The value "' + value + '" is invalid for option "' + name + '"';
- }, TypeError);
- createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
- // determiner: 'must be' or 'must not be'
- var determiner;
- if (typeof expected === 'string' && startsWith(expected, 'not ')) {
- determiner = 'must not be';
- expected = expected.replace(/^not /, '');
- } else {
- determiner = 'must be';
- }
- var msg;
- if (endsWith(name, ' argument')) {
- // For cases like 'first argument'
- msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
- } else {
- var type = includes(name, '.') ? 'property' : 'argument';
- msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
- }
- msg += ". Received type ".concat(typeof actual);
- return msg;
- }, TypeError);
- createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
- createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
- return 'The ' + name + ' method is not implemented';
- });
- createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
- createErrorType('ERR_STREAM_DESTROYED', function (name) {
- return 'Cannot call ' + name + ' after a stream was destroyed';
- });
- createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
- createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
- createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
- createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
- createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
- return 'Unknown encoding: ' + arg;
- }, TypeError);
- createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
- module.exports.codes = codes;
- },{}],340:[function(require,module,exports){
- (function (process){
- 'use strict'
- var experimentalWarnings = new Set();
- function emitExperimentalWarning(feature) {
- if (experimentalWarnings.has(feature)) return;
- var msg = feature + ' is an experimental feature. This feature could ' +
- 'change at any time';
- experimentalWarnings.add(feature);
- process.emitWarning(msg, 'ExperimentalWarning');
- }
- function noop() {}
- module.exports.emitExperimentalWarning = process.emitWarning
- ? emitExperimentalWarning
- : noop;
- }).call(this,require('_process'))
- },{"_process":312}],341:[function(require,module,exports){
- (function (process){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // a duplex stream is just a stream that is both readable and writable.
- // Since JS doesn't have multiple prototypal inheritance, this class
- // prototypally inherits from Readable, and then parasitically from
- // Writable.
- 'use strict';
- /*<replacement>*/
- var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- keys.push(key);
- }
- return keys;
- };
- /*</replacement>*/
- module.exports = Duplex;
- var Readable = require('./_stream_readable');
- var Writable = require('./_stream_writable');
- require('inherits')(Duplex, Readable);
- {
- // Allow the keys array to be GC'ed.
- var keys = objectKeys(Writable.prototype);
- for (var v = 0; v < keys.length; v++) {
- var method = keys[v];
- if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
- }
- }
- function Duplex(options) {
- if (!(this instanceof Duplex)) return new Duplex(options);
- Readable.call(this, options);
- Writable.call(this, options);
- this.allowHalfOpen = true;
- if (options) {
- if (options.readable === false) this.readable = false;
- if (options.writable === false) this.writable = false;
- if (options.allowHalfOpen === false) {
- this.allowHalfOpen = false;
- this.once('end', onend);
- }
- }
- }
- Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- return this._writableState.highWaterMark;
- }
- });
- Object.defineProperty(Duplex.prototype, 'writableBuffer', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- return this._writableState && this._writableState.getBuffer();
- }
- });
- Object.defineProperty(Duplex.prototype, 'writableLength', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- return this._writableState.length;
- }
- }); // the no-half-open enforcer
- function onend() {
- // If the writable side ended, then we're ok.
- if (this._writableState.ended) return; // no more data can be written.
- // But allow more writes to happen in this tick.
- process.nextTick(onEndNT, this);
- }
- function onEndNT(self) {
- self.end();
- }
- Object.defineProperty(Duplex.prototype, 'destroyed', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- if (this._readableState === undefined || this._writableState === undefined) {
- return false;
- }
- return this._readableState.destroyed && this._writableState.destroyed;
- },
- set: function set(value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (this._readableState === undefined || this._writableState === undefined) {
- return;
- } // backward compatibility, the user is explicitly
- // managing destroyed
- this._readableState.destroyed = value;
- this._writableState.destroyed = value;
- }
- });
- }).call(this,require('_process'))
- },{"./_stream_readable":343,"./_stream_writable":345,"_process":312,"inherits":254}],342:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // a passthrough stream.
- // basically just the most minimal sort of Transform stream.
- // Every written chunk gets output as-is.
- 'use strict';
- module.exports = PassThrough;
- var Transform = require('./_stream_transform');
- require('inherits')(PassThrough, Transform);
- function PassThrough(options) {
- if (!(this instanceof PassThrough)) return new PassThrough(options);
- Transform.call(this, options);
- }
- PassThrough.prototype._transform = function (chunk, encoding, cb) {
- cb(null, chunk);
- };
- },{"./_stream_transform":344,"inherits":254}],343:[function(require,module,exports){
- (function (process,global){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- 'use strict';
- module.exports = Readable;
- /*<replacement>*/
- var Duplex;
- /*</replacement>*/
- Readable.ReadableState = ReadableState;
- /*<replacement>*/
- var EE = require('events').EventEmitter;
- var EElistenerCount = function EElistenerCount(emitter, type) {
- return emitter.listeners(type).length;
- };
- /*</replacement>*/
- /*<replacement>*/
- var Stream = require('./internal/streams/stream');
- /*</replacement>*/
- var Buffer = require('buffer').Buffer;
- var OurUint8Array = global.Uint8Array || function () {};
- function _uint8ArrayToBuffer(chunk) {
- return Buffer.from(chunk);
- }
- function _isUint8Array(obj) {
- return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
- }
- /*<replacement>*/
- var debugUtil = require('util');
- var debug;
- if (debugUtil && debugUtil.debuglog) {
- debug = debugUtil.debuglog('stream');
- } else {
- debug = function debug() {};
- }
- /*</replacement>*/
- var BufferList = require('./internal/streams/buffer_list');
- var destroyImpl = require('./internal/streams/destroy');
- var _require = require('./internal/streams/state'),
- getHighWaterMark = _require.getHighWaterMark;
- var _require$codes = require('../errors').codes,
- ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
- ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
- ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
- ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
- var _require2 = require('../experimentalWarning'),
- emitExperimentalWarning = _require2.emitExperimentalWarning; // Lazy loaded to improve the startup performance.
- var StringDecoder;
- var createReadableStreamAsyncIterator;
- require('inherits')(Readable, Stream);
- var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
- function prependListener(emitter, event, fn) {
- // Sadly this is not cacheable as some libraries bundle their own
- // event emitter implementation with them.
- if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
- // userland ones. NEVER DO THIS. This is here only because this code needs
- // to continue to work with older versions of Node.js that do not include
- // the prependListener() method. The goal is to eventually remove this hack.
- if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
- }
- function ReadableState(options, stream, isDuplex) {
- Duplex = Duplex || require('./_stream_duplex');
- options = options || {}; // Duplex streams are both readable and writable, but share
- // the same options object.
- // However, some cases require setting options to different
- // values for the readable and the writable sides of the duplex stream.
- // These options can be provided separately as readableXXX and writableXXX.
- if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
- // make all the buffer merging and length checks go away
- this.objectMode = !!options.objectMode;
- if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
- // Note: 0 is a valid value, means "don't call _read preemptively ever"
- this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
- // linked list can remove elements from the beginning faster than
- // array.shift()
- this.buffer = new BufferList();
- this.length = 0;
- this.pipes = null;
- this.pipesCount = 0;
- this.flowing = null;
- this.ended = false;
- this.endEmitted = false;
- this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
- // immediately, or on a later tick. We set this to true at first, because
- // any actions that shouldn't happen until "later" should generally also
- // not happen before the first read call.
- this.sync = true; // whenever we return null, then we set a flag to say
- // that we're awaiting a 'readable' event emission.
- this.needReadable = false;
- this.emittedReadable = false;
- this.readableListening = false;
- this.resumeScheduled = false;
- this.paused = true; // Should close be emitted on destroy. Defaults to true.
- this.emitClose = options.emitClose !== false; // has it been destroyed
- this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
- this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
- this.readingMore = false;
- this.decoder = null;
- this.encoding = null;
- if (options.encoding) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this.decoder = new StringDecoder(options.encoding);
- this.encoding = options.encoding;
- }
- }
- function Readable(options) {
- Duplex = Duplex || require('./_stream_duplex');
- if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
- // the ReadableState constructor, at least with V8 6.5
- var isDuplex = this instanceof Duplex;
- this._readableState = new ReadableState(options, this, isDuplex); // legacy
- this.readable = true;
- if (options) {
- if (typeof options.read === 'function') this._read = options.read;
- if (typeof options.destroy === 'function') this._destroy = options.destroy;
- }
- Stream.call(this);
- }
- Object.defineProperty(Readable.prototype, 'destroyed', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- if (this._readableState === undefined) {
- return false;
- }
- return this._readableState.destroyed;
- },
- set: function set(value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (!this._readableState) {
- return;
- } // backward compatibility, the user is explicitly
- // managing destroyed
- this._readableState.destroyed = value;
- }
- });
- Readable.prototype.destroy = destroyImpl.destroy;
- Readable.prototype._undestroy = destroyImpl.undestroy;
- Readable.prototype._destroy = function (err, cb) {
- cb(err);
- }; // Manually shove something into the read() buffer.
- // This returns true if the highWaterMark has not been hit yet,
- // similar to how Writable.write() returns true if you should
- // write() some more.
- Readable.prototype.push = function (chunk, encoding) {
- var state = this._readableState;
- var skipChunkCheck;
- if (!state.objectMode) {
- if (typeof chunk === 'string') {
- encoding = encoding || state.defaultEncoding;
- if (encoding !== state.encoding) {
- chunk = Buffer.from(chunk, encoding);
- encoding = '';
- }
- skipChunkCheck = true;
- }
- } else {
- skipChunkCheck = true;
- }
- return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
- }; // Unshift should *always* be something directly out of read()
- Readable.prototype.unshift = function (chunk) {
- return readableAddChunk(this, chunk, null, true, false);
- };
- function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
- debug('readableAddChunk', chunk);
- var state = stream._readableState;
- if (chunk === null) {
- state.reading = false;
- onEofChunk(stream, state);
- } else {
- var er;
- if (!skipChunkCheck) er = chunkInvalid(state, chunk);
- if (er) {
- stream.emit('error', er);
- } else if (state.objectMode || chunk && chunk.length > 0) {
- if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
- chunk = _uint8ArrayToBuffer(chunk);
- }
- if (addToFront) {
- if (state.endEmitted) stream.emit('error', new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
- } else if (state.ended) {
- stream.emit('error', new ERR_STREAM_PUSH_AFTER_EOF());
- } else if (state.destroyed) {
- return false;
- } else {
- state.reading = false;
- if (state.decoder && !encoding) {
- chunk = state.decoder.write(chunk);
- if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
- } else {
- addChunk(stream, state, chunk, false);
- }
- }
- } else if (!addToFront) {
- state.reading = false;
- maybeReadMore(stream, state);
- }
- } // We can push more data if we are below the highWaterMark.
- // Also, if we have no data yet, we can stand some more bytes.
- // This is to work around cases where hwm=0, such as the repl.
- return !state.ended && (state.length < state.highWaterMark || state.length === 0);
- }
- function addChunk(stream, state, chunk, addToFront) {
- if (state.flowing && state.length === 0 && !state.sync) {
- state.awaitDrain = 0;
- stream.emit('data', chunk);
- } else {
- // update the buffer info.
- state.length += state.objectMode ? 1 : chunk.length;
- if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
- if (state.needReadable) emitReadable(stream);
- }
- maybeReadMore(stream, state);
- }
- function chunkInvalid(state, chunk) {
- var er;
- if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
- er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
- }
- return er;
- }
- Readable.prototype.isPaused = function () {
- return this._readableState.flowing === false;
- }; // backwards compatibility.
- Readable.prototype.setEncoding = function (enc) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this._readableState.decoder = new StringDecoder(enc); // if setEncoding(null), decoder.encoding equals utf8
- this._readableState.encoding = this._readableState.decoder.encoding;
- return this;
- }; // Don't raise the hwm > 8MB
- var MAX_HWM = 0x800000;
- function computeNewHighWaterMark(n) {
- if (n >= MAX_HWM) {
- n = MAX_HWM;
- } else {
- // Get the next highest power of 2 to prevent increasing hwm excessively in
- // tiny amounts
- n--;
- n |= n >>> 1;
- n |= n >>> 2;
- n |= n >>> 4;
- n |= n >>> 8;
- n |= n >>> 16;
- n++;
- }
- return n;
- } // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function howMuchToRead(n, state) {
- if (n <= 0 || state.length === 0 && state.ended) return 0;
- if (state.objectMode) return 1;
- if (n !== n) {
- // Only flow one buffer at a time
- if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
- } // If we're asking for more than the current hwm, then raise the hwm.
- if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
- if (n <= state.length) return n; // Don't have enough
- if (!state.ended) {
- state.needReadable = true;
- return 0;
- }
- return state.length;
- } // you can override either this method, or the async _read(n) below.
- Readable.prototype.read = function (n) {
- debug('read', n);
- n = parseInt(n, 10);
- var state = this._readableState;
- var nOrig = n;
- if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
- // already have a bunch of data in the buffer, then just trigger
- // the 'readable' event and move on.
- if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
- debug('read: emitReadable', state.length, state.ended);
- if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
- return null;
- }
- n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
- if (n === 0 && state.ended) {
- if (state.length === 0) endReadable(this);
- return null;
- } // All the actual chunk generation logic needs to be
- // *below* the call to _read. The reason is that in certain
- // synthetic stream cases, such as passthrough streams, _read
- // may be a completely synchronous operation which may change
- // the state of the read buffer, providing enough data when
- // before there was *not* enough.
- //
- // So, the steps are:
- // 1. Figure out what the state of things will be after we do
- // a read from the buffer.
- //
- // 2. If that resulting state will trigger a _read, then call _read.
- // Note that this may be asynchronous, or synchronous. Yes, it is
- // deeply ugly to write APIs this way, but that still doesn't mean
- // that the Readable class should behave improperly, as streams are
- // designed to be sync/async agnostic.
- // Take note if the _read call is sync or async (ie, if the read call
- // has returned yet), so that we know whether or not it's safe to emit
- // 'readable' etc.
- //
- // 3. Actually pull the requested chunks out of the buffer and return.
- // if we need a readable event, then we need to do some reading.
- var doRead = state.needReadable;
- debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
- if (state.length === 0 || state.length - n < state.highWaterMark) {
- doRead = true;
- debug('length less than watermark', doRead);
- } // however, if we've ended, then there's no point, and if we're already
- // reading, then it's unnecessary.
- if (state.ended || state.reading) {
- doRead = false;
- debug('reading or ended', doRead);
- } else if (doRead) {
- debug('do read');
- state.reading = true;
- state.sync = true; // if the length is currently zero, then we *need* a readable event.
- if (state.length === 0) state.needReadable = true; // call internal read method
- this._read(state.highWaterMark);
- state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
- // and we need to re-evaluate how much data we can return to the user.
- if (!state.reading) n = howMuchToRead(nOrig, state);
- }
- var ret;
- if (n > 0) ret = fromList(n, state);else ret = null;
- if (ret === null) {
- state.needReadable = true;
- n = 0;
- } else {
- state.length -= n;
- state.awaitDrain = 0;
- }
- if (state.length === 0) {
- // If we have nothing in the buffer, then we want to know
- // as soon as we *do* get something into the buffer.
- if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
- if (nOrig !== n && state.ended) endReadable(this);
- }
- if (ret !== null) this.emit('data', ret);
- return ret;
- };
- function onEofChunk(stream, state) {
- if (state.ended) return;
- if (state.decoder) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) {
- state.buffer.push(chunk);
- state.length += state.objectMode ? 1 : chunk.length;
- }
- }
- state.ended = true;
- if (state.sync) {
- // if we are sync, wait until next tick to emit the data.
- // Otherwise we risk emitting data in the flow()
- // the readable code triggers during a read() call
- emitReadable(stream);
- } else {
- // emit 'readable' now to make sure it gets picked up.
- state.needReadable = false;
- if (!state.emittedReadable) {
- state.emittedReadable = true;
- emitReadable_(stream);
- }
- }
- } // Don't emit readable right away in sync mode, because this can trigger
- // another read() call => stack overflow. This way, it might trigger
- // a nextTick recursion warning, but that's not so bad.
- function emitReadable(stream) {
- var state = stream._readableState;
- state.needReadable = false;
- if (!state.emittedReadable) {
- debug('emitReadable', state.flowing);
- state.emittedReadable = true;
- process.nextTick(emitReadable_, stream);
- }
- }
- function emitReadable_(stream) {
- var state = stream._readableState;
- debug('emitReadable_', state.destroyed, state.length, state.ended);
- if (!state.destroyed && (state.length || state.ended)) {
- stream.emit('readable');
- } // The stream needs another readable event if
- // 1. It is not flowing, as the flow mechanism will take
- // care of it.
- // 2. It is not ended.
- // 3. It is below the highWaterMark, so we can schedule
- // another readable later.
- state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
- flow(stream);
- } // at this point, the user has presumably seen the 'readable' event,
- // and called read() to consume some data. that may have triggered
- // in turn another _read(n) call, in which case reading = true if
- // it's in progress.
- // However, if we're not ended, or reading, and the length < hwm,
- // then go ahead and try to read some more preemptively.
- function maybeReadMore(stream, state) {
- if (!state.readingMore) {
- state.readingMore = true;
- process.nextTick(maybeReadMore_, stream, state);
- }
- }
- function maybeReadMore_(stream, state) {
- // Attempt to read more data if we should.
- //
- // The conditions for reading more data are (one of):
- // - Not enough data buffered (state.length < state.highWaterMark). The loop
- // is responsible for filling the buffer with enough data if such data
- // is available. If highWaterMark is 0 and we are not in the flowing mode
- // we should _not_ attempt to buffer any extra data. We'll get more data
- // when the stream consumer calls read() instead.
- // - No data in the buffer, and the stream is in flowing mode. In this mode
- // the loop below is responsible for ensuring read() is called. Failing to
- // call read here would abort the flow and there's no other mechanism for
- // continuing the flow if the stream consumer has just subscribed to the
- // 'data' event.
- //
- // In addition to the above conditions to keep reading data, the following
- // conditions prevent the data from being read:
- // - The stream has ended (state.ended).
- // - There is already a pending 'read' operation (state.reading). This is a
- // case where the the stream has called the implementation defined _read()
- // method, but they are processing the call asynchronously and have _not_
- // called push() with new data. In this case we skip performing more
- // read()s. The execution ends in this method again after the _read() ends
- // up calling push() with more data.
- while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
- var len = state.length;
- debug('maybeReadMore read 0');
- stream.read(0);
- if (len === state.length) // didn't get any data, stop spinning.
- break;
- }
- state.readingMore = false;
- } // abstract method. to be overridden in specific implementation classes.
- // call cb(er, data) where data is <= n in length.
- // for virtual (non-string, non-buffer) streams, "length" is somewhat
- // arbitrary, and perhaps not very meaningful.
- Readable.prototype._read = function (n) {
- this.emit('error', new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
- };
- Readable.prototype.pipe = function (dest, pipeOpts) {
- var src = this;
- var state = this._readableState;
- switch (state.pipesCount) {
- case 0:
- state.pipes = dest;
- break;
- case 1:
- state.pipes = [state.pipes, dest];
- break;
- default:
- state.pipes.push(dest);
- break;
- }
- state.pipesCount += 1;
- debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
- var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
- var endFn = doEnd ? onend : unpipe;
- if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
- dest.on('unpipe', onunpipe);
- function onunpipe(readable, unpipeInfo) {
- debug('onunpipe');
- if (readable === src) {
- if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
- unpipeInfo.hasUnpiped = true;
- cleanup();
- }
- }
- }
- function onend() {
- debug('onend');
- dest.end();
- } // when the dest drains, it reduces the awaitDrain counter
- // on the source. This would be more elegant with a .once()
- // handler in flow(), but adding and removing repeatedly is
- // too slow.
- var ondrain = pipeOnDrain(src);
- dest.on('drain', ondrain);
- var cleanedUp = false;
- function cleanup() {
- debug('cleanup'); // cleanup event handlers once the pipe is broken
- dest.removeListener('close', onclose);
- dest.removeListener('finish', onfinish);
- dest.removeListener('drain', ondrain);
- dest.removeListener('error', onerror);
- dest.removeListener('unpipe', onunpipe);
- src.removeListener('end', onend);
- src.removeListener('end', unpipe);
- src.removeListener('data', ondata);
- cleanedUp = true; // if the reader is waiting for a drain event from this
- // specific writer, then it would cause it to never start
- // flowing again.
- // So, if this is awaiting a drain, then we just call it now.
- // If we don't know, then assume that we are waiting for one.
- if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
- }
- src.on('data', ondata);
- function ondata(chunk) {
- debug('ondata');
- var ret = dest.write(chunk);
- debug('dest.write', ret);
- if (ret === false) {
- // If the user unpiped during `dest.write()`, it is possible
- // to get stuck in a permanently paused state if that write
- // also returned false.
- // => Check whether `dest` is still a piping destination.
- if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
- debug('false write response, pause', state.awaitDrain);
- state.awaitDrain++;
- }
- src.pause();
- }
- } // if the dest has an error, then stop piping into it.
- // however, don't suppress the throwing behavior for this.
- function onerror(er) {
- debug('onerror', er);
- unpipe();
- dest.removeListener('error', onerror);
- if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
- } // Make sure our error handler is attached before userland ones.
- prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
- function onclose() {
- dest.removeListener('finish', onfinish);
- unpipe();
- }
- dest.once('close', onclose);
- function onfinish() {
- debug('onfinish');
- dest.removeListener('close', onclose);
- unpipe();
- }
- dest.once('finish', onfinish);
- function unpipe() {
- debug('unpipe');
- src.unpipe(dest);
- } // tell the dest that it's being piped to
- dest.emit('pipe', src); // start the flow if it hasn't been started already.
- if (!state.flowing) {
- debug('pipe resume');
- src.resume();
- }
- return dest;
- };
- function pipeOnDrain(src) {
- return function pipeOnDrainFunctionResult() {
- var state = src._readableState;
- debug('pipeOnDrain', state.awaitDrain);
- if (state.awaitDrain) state.awaitDrain--;
- if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
- state.flowing = true;
- flow(src);
- }
- };
- }
- Readable.prototype.unpipe = function (dest) {
- var state = this._readableState;
- var unpipeInfo = {
- hasUnpiped: false
- }; // if we're not piping anywhere, then do nothing.
- if (state.pipesCount === 0) return this; // just one destination. most common case.
- if (state.pipesCount === 1) {
- // passed in one, but it's not the right one.
- if (dest && dest !== state.pipes) return this;
- if (!dest) dest = state.pipes; // got a match.
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
- if (dest) dest.emit('unpipe', this, unpipeInfo);
- return this;
- } // slow case. multiple pipe destinations.
- if (!dest) {
- // remove all.
- var dests = state.pipes;
- var len = state.pipesCount;
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
- for (var i = 0; i < len; i++) {
- dests[i].emit('unpipe', this, {
- hasUnpiped: false
- });
- }
- return this;
- } // try to find the right one.
- var index = indexOf(state.pipes, dest);
- if (index === -1) return this;
- state.pipes.splice(index, 1);
- state.pipesCount -= 1;
- if (state.pipesCount === 1) state.pipes = state.pipes[0];
- dest.emit('unpipe', this, unpipeInfo);
- return this;
- }; // set up data events if they are asked for
- // Ensure readable listeners eventually get something
- Readable.prototype.on = function (ev, fn) {
- var res = Stream.prototype.on.call(this, ev, fn);
- var state = this._readableState;
- if (ev === 'data') {
- // update readableListening so that resume() may be a no-op
- // a few lines down. This is needed to support once('readable').
- state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
- if (state.flowing !== false) this.resume();
- } else if (ev === 'readable') {
- if (!state.endEmitted && !state.readableListening) {
- state.readableListening = state.needReadable = true;
- state.flowing = false;
- state.emittedReadable = false;
- debug('on readable', state.length, state.reading);
- if (state.length) {
- emitReadable(this);
- } else if (!state.reading) {
- process.nextTick(nReadingNextTick, this);
- }
- }
- }
- return res;
- };
- Readable.prototype.addListener = Readable.prototype.on;
- Readable.prototype.removeListener = function (ev, fn) {
- var res = Stream.prototype.removeListener.call(this, ev, fn);
- if (ev === 'readable') {
- // We need to check if there is someone still listening to
- // readable and reset the state. However this needs to happen
- // after readable has been emitted but before I/O (nextTick) to
- // support once('readable', fn) cycles. This means that calling
- // resume within the same tick will have no
- // effect.
- process.nextTick(updateReadableListening, this);
- }
- return res;
- };
- Readable.prototype.removeAllListeners = function (ev) {
- var res = Stream.prototype.removeAllListeners.apply(this, arguments);
- if (ev === 'readable' || ev === undefined) {
- // We need to check if there is someone still listening to
- // readable and reset the state. However this needs to happen
- // after readable has been emitted but before I/O (nextTick) to
- // support once('readable', fn) cycles. This means that calling
- // resume within the same tick will have no
- // effect.
- process.nextTick(updateReadableListening, this);
- }
- return res;
- };
- function updateReadableListening(self) {
- var state = self._readableState;
- state.readableListening = self.listenerCount('readable') > 0;
- if (state.resumeScheduled && !state.paused) {
- // flowing needs to be set to true now, otherwise
- // the upcoming resume will not flow.
- state.flowing = true; // crude way to check if we should resume
- } else if (self.listenerCount('data') > 0) {
- self.resume();
- }
- }
- function nReadingNextTick(self) {
- debug('readable nexttick read 0');
- self.read(0);
- } // pause() and resume() are remnants of the legacy readable stream API
- // If the user uses them, then switch into old mode.
- Readable.prototype.resume = function () {
- var state = this._readableState;
- if (!state.flowing) {
- debug('resume'); // we flow only if there is no one listening
- // for readable, but we still have to call
- // resume()
- state.flowing = !state.readableListening;
- resume(this, state);
- }
- state.paused = false;
- return this;
- };
- function resume(stream, state) {
- if (!state.resumeScheduled) {
- state.resumeScheduled = true;
- process.nextTick(resume_, stream, state);
- }
- }
- function resume_(stream, state) {
- debug('resume', state.reading);
- if (!state.reading) {
- stream.read(0);
- }
- state.resumeScheduled = false;
- stream.emit('resume');
- flow(stream);
- if (state.flowing && !state.reading) stream.read(0);
- }
- Readable.prototype.pause = function () {
- debug('call pause flowing=%j', this._readableState.flowing);
- if (this._readableState.flowing !== false) {
- debug('pause');
- this._readableState.flowing = false;
- this.emit('pause');
- }
- this._readableState.paused = true;
- return this;
- };
- function flow(stream) {
- var state = stream._readableState;
- debug('flow', state.flowing);
- while (state.flowing && stream.read() !== null) {
- ;
- }
- } // wrap an old-style stream as the async data source.
- // This is *not* part of the readable stream interface.
- // It is an ugly unfortunate mess of history.
- Readable.prototype.wrap = function (stream) {
- var _this = this;
- var state = this._readableState;
- var paused = false;
- stream.on('end', function () {
- debug('wrapped end');
- if (state.decoder && !state.ended) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) _this.push(chunk);
- }
- _this.push(null);
- });
- stream.on('data', function (chunk) {
- debug('wrapped data');
- if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
- if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
- var ret = _this.push(chunk);
- if (!ret) {
- paused = true;
- stream.pause();
- }
- }); // proxy all the other methods.
- // important when wrapping filters and duplexes.
- for (var i in stream) {
- if (this[i] === undefined && typeof stream[i] === 'function') {
- this[i] = function methodWrap(method) {
- return function methodWrapReturnFunction() {
- return stream[method].apply(stream, arguments);
- };
- }(i);
- }
- } // proxy certain important events.
- for (var n = 0; n < kProxyEvents.length; n++) {
- stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
- } // when we try to consume some more bytes, simply unpause the
- // underlying stream.
- this._read = function (n) {
- debug('wrapped _read', n);
- if (paused) {
- paused = false;
- stream.resume();
- }
- };
- return this;
- };
- if (typeof Symbol === 'function') {
- Readable.prototype[Symbol.asyncIterator] = function () {
- emitExperimentalWarning('Readable[Symbol.asyncIterator]');
- if (createReadableStreamAsyncIterator === undefined) {
- createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
- }
- return createReadableStreamAsyncIterator(this);
- };
- }
- Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- return this._readableState.highWaterMark;
- }
- });
- Object.defineProperty(Readable.prototype, 'readableBuffer', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- return this._readableState && this._readableState.buffer;
- }
- });
- Object.defineProperty(Readable.prototype, 'readableFlowing', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- return this._readableState.flowing;
- },
- set: function set(state) {
- if (this._readableState) {
- this._readableState.flowing = state;
- }
- }
- }); // exposed for testing purposes only.
- Readable._fromList = fromList;
- Object.defineProperty(Readable.prototype, 'readableLength', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- return this._readableState.length;
- }
- }); // Pluck off n bytes from an array of buffers.
- // Length is the combined lengths of all the buffers in the list.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function fromList(n, state) {
- // nothing buffered
- if (state.length === 0) return null;
- var ret;
- if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
- // read it all, truncate the list
- if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
- state.buffer.clear();
- } else {
- // read part of list
- ret = state.buffer.consume(n, state.decoder);
- }
- return ret;
- }
- function endReadable(stream) {
- var state = stream._readableState;
- debug('endReadable', state.endEmitted);
- if (!state.endEmitted) {
- state.ended = true;
- process.nextTick(endReadableNT, state, stream);
- }
- }
- function endReadableNT(state, stream) {
- debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
- if (!state.endEmitted && state.length === 0) {
- state.endEmitted = true;
- stream.readable = false;
- stream.emit('end');
- }
- }
- function indexOf(xs, x) {
- for (var i = 0, l = xs.length; i < l; i++) {
- if (xs[i] === x) return i;
- }
- return -1;
- }
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"../errors":339,"../experimentalWarning":340,"./_stream_duplex":341,"./internal/streams/async_iterator":346,"./internal/streams/buffer_list":347,"./internal/streams/destroy":348,"./internal/streams/state":351,"./internal/streams/stream":352,"_process":312,"buffer":47,"events":239,"inherits":254,"string_decoder/":354,"util":32}],344:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // a transform stream is a readable/writable stream where you do
- // something with the data. Sometimes it's called a "filter",
- // but that's not a great name for it, since that implies a thing where
- // some bits pass through, and others are simply ignored. (That would
- // be a valid example of a transform, of course.)
- //
- // While the output is causally related to the input, it's not a
- // necessarily symmetric or synchronous transformation. For example,
- // a zlib stream might take multiple plain-text writes(), and then
- // emit a single compressed chunk some time in the future.
- //
- // Here's how this works:
- //
- // The Transform stream has all the aspects of the readable and writable
- // stream classes. When you write(chunk), that calls _write(chunk,cb)
- // internally, and returns false if there's a lot of pending writes
- // buffered up. When you call read(), that calls _read(n) until
- // there's enough pending readable data buffered up.
- //
- // In a transform stream, the written data is placed in a buffer. When
- // _read(n) is called, it transforms the queued up data, calling the
- // buffered _write cb's as it consumes chunks. If consuming a single
- // written chunk would result in multiple output chunks, then the first
- // outputted bit calls the readcb, and subsequent chunks just go into
- // the read buffer, and will cause it to emit 'readable' if necessary.
- //
- // This way, back-pressure is actually determined by the reading side,
- // since _read has to be called to start processing a new chunk. However,
- // a pathological inflate type of transform can cause excessive buffering
- // here. For example, imagine a stream where every byte of input is
- // interpreted as an integer from 0-255, and then results in that many
- // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
- // 1kb of data being output. In this case, you could write a very small
- // amount of input, and end up with a very large amount of output. In
- // such a pathological inflating mechanism, there'd be no way to tell
- // the system to stop doing the transform. A single 4MB write could
- // cause the system to run out of memory.
- //
- // However, even in such a pathological case, only a single written chunk
- // would be consumed, and then the rest would wait (un-transformed) until
- // the results of the previous transformed chunk were consumed.
- 'use strict';
- module.exports = Transform;
- var _require$codes = require('../errors').codes,
- ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
- ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
- ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
- ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
- var Duplex = require('./_stream_duplex');
- require('inherits')(Transform, Duplex);
- function afterTransform(er, data) {
- var ts = this._transformState;
- ts.transforming = false;
- var cb = ts.writecb;
- if (cb === null) {
- return this.emit('error', new ERR_MULTIPLE_CALLBACK());
- }
- ts.writechunk = null;
- ts.writecb = null;
- if (data != null) // single equals check for both `null` and `undefined`
- this.push(data);
- cb(er);
- var rs = this._readableState;
- rs.reading = false;
- if (rs.needReadable || rs.length < rs.highWaterMark) {
- this._read(rs.highWaterMark);
- }
- }
- function Transform(options) {
- if (!(this instanceof Transform)) return new Transform(options);
- Duplex.call(this, options);
- this._transformState = {
- afterTransform: afterTransform.bind(this),
- needTransform: false,
- transforming: false,
- writecb: null,
- writechunk: null,
- writeencoding: null
- }; // start out asking for a readable event once data is transformed.
- this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
- // that Readable wants before the first _read call, so unset the
- // sync guard flag.
- this._readableState.sync = false;
- if (options) {
- if (typeof options.transform === 'function') this._transform = options.transform;
- if (typeof options.flush === 'function') this._flush = options.flush;
- } // When the writable side finishes, then flush out anything remaining.
- this.on('prefinish', prefinish);
- }
- function prefinish() {
- var _this = this;
- if (typeof this._flush === 'function' && !this._readableState.destroyed) {
- this._flush(function (er, data) {
- done(_this, er, data);
- });
- } else {
- done(this, null, null);
- }
- }
- Transform.prototype.push = function (chunk, encoding) {
- this._transformState.needTransform = false;
- return Duplex.prototype.push.call(this, chunk, encoding);
- }; // This is the part where you do stuff!
- // override this function in implementation classes.
- // 'chunk' is an input chunk.
- //
- // Call `push(newChunk)` to pass along transformed output
- // to the readable side. You may call 'push' zero or more times.
- //
- // Call `cb(err)` when you are done with this chunk. If you pass
- // an error, then that'll put the hurt on the whole operation. If you
- // never call cb(), then you'll never get another chunk.
- Transform.prototype._transform = function (chunk, encoding, cb) {
- cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
- };
- Transform.prototype._write = function (chunk, encoding, cb) {
- var ts = this._transformState;
- ts.writecb = cb;
- ts.writechunk = chunk;
- ts.writeencoding = encoding;
- if (!ts.transforming) {
- var rs = this._readableState;
- if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
- }
- }; // Doesn't matter what the args are here.
- // _transform does all the work.
- // That we got here means that the readable side wants more data.
- Transform.prototype._read = function (n) {
- var ts = this._transformState;
- if (ts.writechunk !== null && !ts.transforming) {
- ts.transforming = true;
- this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
- } else {
- // mark that we need a transform, so that any data that comes in
- // will get processed, now that we've asked for it.
- ts.needTransform = true;
- }
- };
- Transform.prototype._destroy = function (err, cb) {
- Duplex.prototype._destroy.call(this, err, function (err2) {
- cb(err2);
- });
- };
- function done(stream, er, data) {
- if (er) return stream.emit('error', er);
- if (data != null) // single equals check for both `null` and `undefined`
- stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
- // if there's nothing in the write buffer, then that means
- // that nothing more will ever be provided
- if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
- if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
- return stream.push(null);
- }
- },{"../errors":339,"./_stream_duplex":341,"inherits":254}],345:[function(require,module,exports){
- (function (process,global){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // A bit simpler than readable streams.
- // Implement an async ._write(chunk, encoding, cb), and it'll handle all
- // the drain event emission and buffering.
- 'use strict';
- module.exports = Writable;
- /* <replacement> */
- function WriteReq(chunk, encoding, cb) {
- this.chunk = chunk;
- this.encoding = encoding;
- this.callback = cb;
- this.next = null;
- } // It seems a linked list but it is not
- // there will be only 2 of these for each stream
- function CorkedRequest(state) {
- var _this = this;
- this.next = null;
- this.entry = null;
- this.finish = function () {
- onCorkedFinish(_this, state);
- };
- }
- /* </replacement> */
- /*<replacement>*/
- var Duplex;
- /*</replacement>*/
- Writable.WritableState = WritableState;
- /*<replacement>*/
- var internalUtil = {
- deprecate: require('util-deprecate')
- };
- /*</replacement>*/
- /*<replacement>*/
- var Stream = require('./internal/streams/stream');
- /*</replacement>*/
- var Buffer = require('buffer').Buffer;
- var OurUint8Array = global.Uint8Array || function () {};
- function _uint8ArrayToBuffer(chunk) {
- return Buffer.from(chunk);
- }
- function _isUint8Array(obj) {
- return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
- }
- var destroyImpl = require('./internal/streams/destroy');
- var _require = require('./internal/streams/state'),
- getHighWaterMark = _require.getHighWaterMark;
- var _require$codes = require('../errors').codes,
- ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
- ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
- ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
- ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
- ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
- ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
- ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
- ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
- require('inherits')(Writable, Stream);
- function nop() {}
- function WritableState(options, stream, isDuplex) {
- Duplex = Duplex || require('./_stream_duplex');
- options = options || {}; // Duplex streams are both readable and writable, but share
- // the same options object.
- // However, some cases require setting options to different
- // values for the readable and the writable sides of the duplex stream,
- // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
- if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
- // contains buffers or objects.
- this.objectMode = !!options.objectMode;
- if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
- // Note: 0 is a valid value, means that we always return false if
- // the entire buffer is not flushed immediately on write()
- this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
- this.finalCalled = false; // drain event flag.
- this.needDrain = false; // at the start of calling end()
- this.ending = false; // when end() has been called, and returned
- this.ended = false; // when 'finish' is emitted
- this.finished = false; // has it been destroyed
- this.destroyed = false; // should we decode strings into buffers before passing to _write?
- // this is here so that some node-core streams can optimize string
- // handling at a lower level.
- var noDecode = options.decodeStrings === false;
- this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
- // of how much we're waiting to get pushed to some underlying
- // socket or file.
- this.length = 0; // a flag to see when we're in the middle of a write.
- this.writing = false; // when true all writes will be buffered until .uncork() call
- this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true; // a flag to know if we're processing previously buffered items, which
- // may call the _write() callback in the same tick, so that we don't
- // end up in an overlapped onwrite situation.
- this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
- this.onwrite = function (er) {
- onwrite(stream, er);
- }; // the callback that the user supplies to write(chunk,encoding,cb)
- this.writecb = null; // the amount that is being written when _write is called.
- this.writelen = 0;
- this.bufferedRequest = null;
- this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
- // this must be 0 before 'finish' can be emitted
- this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
- // This is relevant for synchronous Transform streams
- this.prefinished = false; // True if the error was already emitted and should not be thrown again
- this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
- this.emitClose = options.emitClose !== false; // count buffered requests
- this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
- // one allocated and free to use, and we maintain at most two
- this.corkedRequestsFree = new CorkedRequest(this);
- }
- WritableState.prototype.getBuffer = function getBuffer() {
- var current = this.bufferedRequest;
- var out = [];
- while (current) {
- out.push(current);
- current = current.next;
- }
- return out;
- };
- (function () {
- try {
- Object.defineProperty(WritableState.prototype, 'buffer', {
- get: internalUtil.deprecate(function writableStateBufferGetter() {
- return this.getBuffer();
- }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
- });
- } catch (_) {}
- })(); // Test _writableState for inheritance to account for Duplex streams,
- // whose prototype chain only points to Readable.
- var realHasInstance;
- if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
- realHasInstance = Function.prototype[Symbol.hasInstance];
- Object.defineProperty(Writable, Symbol.hasInstance, {
- value: function value(object) {
- if (realHasInstance.call(this, object)) return true;
- if (this !== Writable) return false;
- return object && object._writableState instanceof WritableState;
- }
- });
- } else {
- realHasInstance = function realHasInstance(object) {
- return object instanceof this;
- };
- }
- function Writable(options) {
- Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
- // `realHasInstance` is necessary because using plain `instanceof`
- // would return false, as no `_writableState` property is attached.
- // Trying to use the custom `instanceof` for Writable here will also break the
- // Node.js LazyTransform implementation, which has a non-trivial getter for
- // `_writableState` that would lead to infinite recursion.
- // Checking for a Stream.Duplex instance is faster here instead of inside
- // the WritableState constructor, at least with V8 6.5
- var isDuplex = this instanceof Duplex;
- if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
- this._writableState = new WritableState(options, this, isDuplex); // legacy.
- this.writable = true;
- if (options) {
- if (typeof options.write === 'function') this._write = options.write;
- if (typeof options.writev === 'function') this._writev = options.writev;
- if (typeof options.destroy === 'function') this._destroy = options.destroy;
- if (typeof options.final === 'function') this._final = options.final;
- }
- Stream.call(this);
- } // Otherwise people can pipe Writable streams, which is just wrong.
- Writable.prototype.pipe = function () {
- this.emit('error', new ERR_STREAM_CANNOT_PIPE());
- };
- function writeAfterEnd(stream, cb) {
- var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
- stream.emit('error', er);
- process.nextTick(cb, er);
- } // Checks that a user-supplied chunk is valid, especially for the particular
- // mode the stream is in. Currently this means that `null` is never accepted
- // and undefined/non-string values are only allowed in object mode.
- function validChunk(stream, state, chunk, cb) {
- var er;
- if (chunk === null) {
- er = new ERR_STREAM_NULL_VALUES();
- } else if (typeof chunk !== 'string' && !state.objectMode) {
- er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
- }
- if (er) {
- stream.emit('error', er);
- process.nextTick(cb, er);
- return false;
- }
- return true;
- }
- Writable.prototype.write = function (chunk, encoding, cb) {
- var state = this._writableState;
- var ret = false;
- var isBuf = !state.objectMode && _isUint8Array(chunk);
- if (isBuf && !Buffer.isBuffer(chunk)) {
- chunk = _uint8ArrayToBuffer(chunk);
- }
- if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
- if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
- if (typeof cb !== 'function') cb = nop;
- if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
- state.pendingcb++;
- ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
- }
- return ret;
- };
- Writable.prototype.cork = function () {
- this._writableState.corked++;
- };
- Writable.prototype.uncork = function () {
- var state = this._writableState;
- if (state.corked) {
- state.corked--;
- if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
- }
- };
- Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
- // node::ParseEncoding() requires lower case.
- if (typeof encoding === 'string') encoding = encoding.toLowerCase();
- if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
- this._writableState.defaultEncoding = encoding;
- return this;
- };
- Object.defineProperty(Writable.prototype, 'writableBuffer', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- return this._writableState && this._writableState.getBuffer();
- }
- });
- function decodeChunk(state, chunk, encoding) {
- if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
- chunk = Buffer.from(chunk, encoding);
- }
- return chunk;
- }
- Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- return this._writableState.highWaterMark;
- }
- }); // if we're already writing something, then just put this
- // in the queue, and wait our turn. Otherwise, call _write
- // If we return false, then we need a drain event, so set that flag.
- function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
- if (!isBuf) {
- var newChunk = decodeChunk(state, chunk, encoding);
- if (chunk !== newChunk) {
- isBuf = true;
- encoding = 'buffer';
- chunk = newChunk;
- }
- }
- var len = state.objectMode ? 1 : chunk.length;
- state.length += len;
- var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
- if (!ret) state.needDrain = true;
- if (state.writing || state.corked) {
- var last = state.lastBufferedRequest;
- state.lastBufferedRequest = {
- chunk: chunk,
- encoding: encoding,
- isBuf: isBuf,
- callback: cb,
- next: null
- };
- if (last) {
- last.next = state.lastBufferedRequest;
- } else {
- state.bufferedRequest = state.lastBufferedRequest;
- }
- state.bufferedRequestCount += 1;
- } else {
- doWrite(stream, state, false, len, chunk, encoding, cb);
- }
- return ret;
- }
- function doWrite(stream, state, writev, len, chunk, encoding, cb) {
- state.writelen = len;
- state.writecb = cb;
- state.writing = true;
- state.sync = true;
- if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
- state.sync = false;
- }
- function onwriteError(stream, state, sync, er, cb) {
- --state.pendingcb;
- if (sync) {
- // defer the callback if we are being called synchronously
- // to avoid piling up things on the stack
- process.nextTick(cb, er); // this can emit finish, and it will always happen
- // after error
- process.nextTick(finishMaybe, stream, state);
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
- } else {
- // the caller expect this to happen before if
- // it is async
- cb(er);
- stream._writableState.errorEmitted = true;
- stream.emit('error', er); // this can emit finish, but finish must
- // always follow error
- finishMaybe(stream, state);
- }
- }
- function onwriteStateUpdate(state) {
- state.writing = false;
- state.writecb = null;
- state.length -= state.writelen;
- state.writelen = 0;
- }
- function onwrite(stream, er) {
- var state = stream._writableState;
- var sync = state.sync;
- var cb = state.writecb;
- if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
- onwriteStateUpdate(state);
- if (er) onwriteError(stream, state, sync, er, cb);else {
- // Check if we're actually ready to finish, but don't emit yet
- var finished = needFinish(state) || stream.destroyed;
- if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
- clearBuffer(stream, state);
- }
- if (sync) {
- process.nextTick(afterWrite, stream, state, finished, cb);
- } else {
- afterWrite(stream, state, finished, cb);
- }
- }
- }
- function afterWrite(stream, state, finished, cb) {
- if (!finished) onwriteDrain(stream, state);
- state.pendingcb--;
- cb();
- finishMaybe(stream, state);
- } // Must force callback to be called on nextTick, so that we don't
- // emit 'drain' before the write() consumer gets the 'false' return
- // value, and has a chance to attach a 'drain' listener.
- function onwriteDrain(stream, state) {
- if (state.length === 0 && state.needDrain) {
- state.needDrain = false;
- stream.emit('drain');
- }
- } // if there's something in the buffer waiting, then process it
- function clearBuffer(stream, state) {
- state.bufferProcessing = true;
- var entry = state.bufferedRequest;
- if (stream._writev && entry && entry.next) {
- // Fast case, write everything using _writev()
- var l = state.bufferedRequestCount;
- var buffer = new Array(l);
- var holder = state.corkedRequestsFree;
- holder.entry = entry;
- var count = 0;
- var allBuffers = true;
- while (entry) {
- buffer[count] = entry;
- if (!entry.isBuf) allBuffers = false;
- entry = entry.next;
- count += 1;
- }
- buffer.allBuffers = allBuffers;
- doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
- // as the hot path ends with doWrite
- state.pendingcb++;
- state.lastBufferedRequest = null;
- if (holder.next) {
- state.corkedRequestsFree = holder.next;
- holder.next = null;
- } else {
- state.corkedRequestsFree = new CorkedRequest(state);
- }
- state.bufferedRequestCount = 0;
- } else {
- // Slow case, write chunks one-by-one
- while (entry) {
- var chunk = entry.chunk;
- var encoding = entry.encoding;
- var cb = entry.callback;
- var len = state.objectMode ? 1 : chunk.length;
- doWrite(stream, state, false, len, chunk, encoding, cb);
- entry = entry.next;
- state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
- // it means that we need to wait until it does.
- // also, that means that the chunk and cb are currently
- // being processed, so move the buffer counter past them.
- if (state.writing) {
- break;
- }
- }
- if (entry === null) state.lastBufferedRequest = null;
- }
- state.bufferedRequest = entry;
- state.bufferProcessing = false;
- }
- Writable.prototype._write = function (chunk, encoding, cb) {
- cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
- };
- Writable.prototype._writev = null;
- Writable.prototype.end = function (chunk, encoding, cb) {
- var state = this._writableState;
- if (typeof chunk === 'function') {
- cb = chunk;
- chunk = null;
- encoding = null;
- } else if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
- if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
- if (state.corked) {
- state.corked = 1;
- this.uncork();
- } // ignore unnecessary end() calls.
- if (!state.ending) endWritable(this, state, cb);
- return this;
- };
- Object.defineProperty(Writable.prototype, 'writableLength', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- return this._writableState.length;
- }
- });
- function needFinish(state) {
- return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
- }
- function callFinal(stream, state) {
- stream._final(function (err) {
- state.pendingcb--;
- if (err) {
- stream.emit('error', err);
- }
- state.prefinished = true;
- stream.emit('prefinish');
- finishMaybe(stream, state);
- });
- }
- function prefinish(stream, state) {
- if (!state.prefinished && !state.finalCalled) {
- if (typeof stream._final === 'function' && !state.destroyed) {
- state.pendingcb++;
- state.finalCalled = true;
- process.nextTick(callFinal, stream, state);
- } else {
- state.prefinished = true;
- stream.emit('prefinish');
- }
- }
- }
- function finishMaybe(stream, state) {
- var need = needFinish(state);
- if (need) {
- prefinish(stream, state);
- if (state.pendingcb === 0) {
- state.finished = true;
- stream.emit('finish');
- }
- }
- return need;
- }
- function endWritable(stream, state, cb) {
- state.ending = true;
- finishMaybe(stream, state);
- if (cb) {
- if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
- }
- state.ended = true;
- stream.writable = false;
- }
- function onCorkedFinish(corkReq, state, err) {
- var entry = corkReq.entry;
- corkReq.entry = null;
- while (entry) {
- var cb = entry.callback;
- state.pendingcb--;
- cb(err);
- entry = entry.next;
- } // reuse the free corkReq.
- state.corkedRequestsFree.next = corkReq;
- }
- Object.defineProperty(Writable.prototype, 'destroyed', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function get() {
- if (this._writableState === undefined) {
- return false;
- }
- return this._writableState.destroyed;
- },
- set: function set(value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (!this._writableState) {
- return;
- } // backward compatibility, the user is explicitly
- // managing destroyed
- this._writableState.destroyed = value;
- }
- });
- Writable.prototype.destroy = destroyImpl.destroy;
- Writable.prototype._undestroy = destroyImpl.undestroy;
- Writable.prototype._destroy = function (err, cb) {
- cb(err);
- };
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"../errors":339,"./_stream_duplex":341,"./internal/streams/destroy":348,"./internal/streams/state":351,"./internal/streams/stream":352,"_process":312,"buffer":47,"inherits":254,"util-deprecate":362}],346:[function(require,module,exports){
- (function (process){
- 'use strict';
- var _Object$setPrototypeO;
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var finished = require('./end-of-stream');
- var kLastResolve = Symbol('lastResolve');
- var kLastReject = Symbol('lastReject');
- var kError = Symbol('error');
- var kEnded = Symbol('ended');
- var kLastPromise = Symbol('lastPromise');
- var kHandlePromise = Symbol('handlePromise');
- var kStream = Symbol('stream');
- function createIterResult(value, done) {
- return {
- value: value,
- done: done
- };
- }
- function readAndResolve(iter) {
- var resolve = iter[kLastResolve];
- if (resolve !== null) {
- var data = iter[kStream].read(); // we defer if data is null
- // we can be expecting either 'end' or
- // 'error'
- if (data !== null) {
- iter[kLastPromise] = null;
- iter[kLastResolve] = null;
- iter[kLastReject] = null;
- resolve(createIterResult(data, false));
- }
- }
- }
- function onReadable(iter) {
- // we wait for the next tick, because it might
- // emit an error with process.nextTick
- process.nextTick(readAndResolve, iter);
- }
- function wrapForNext(lastPromise, iter) {
- return function (resolve, reject) {
- lastPromise.then(function () {
- if (iter[kEnded]) {
- resolve(createIterResult(undefined, true));
- return;
- }
- iter[kHandlePromise](resolve, reject);
- }, reject);
- };
- }
- var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
- var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
- get stream() {
- return this[kStream];
- },
- next: function next() {
- var _this = this;
- // if we have detected an error in the meanwhile
- // reject straight away
- var error = this[kError];
- if (error !== null) {
- return Promise.reject(error);
- }
- if (this[kEnded]) {
- return Promise.resolve(createIterResult(undefined, true));
- }
- if (this[kStream].destroyed) {
- // We need to defer via nextTick because if .destroy(err) is
- // called, the error will be emitted via nextTick, and
- // we cannot guarantee that there is no error lingering around
- // waiting to be emitted.
- return new Promise(function (resolve, reject) {
- process.nextTick(function () {
- if (_this[kError]) {
- reject(_this[kError]);
- } else {
- resolve(createIterResult(undefined, true));
- }
- });
- });
- } // if we have multiple next() calls
- // we will wait for the previous Promise to finish
- // this logic is optimized to support for await loops,
- // where next() is only called once at a time
- var lastPromise = this[kLastPromise];
- var promise;
- if (lastPromise) {
- promise = new Promise(wrapForNext(lastPromise, this));
- } else {
- // fast path needed to support multiple this.push()
- // without triggering the next() queue
- var data = this[kStream].read();
- if (data !== null) {
- return Promise.resolve(createIterResult(data, false));
- }
- promise = new Promise(this[kHandlePromise]);
- }
- this[kLastPromise] = promise;
- return promise;
- }
- }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
- return this;
- }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
- var _this2 = this;
- // destroy(err, cb) is a private API
- // we can guarantee we have that here, because we control the
- // Readable class this is attached to
- return new Promise(function (resolve, reject) {
- _this2[kStream].destroy(null, function (err) {
- if (err) {
- reject(err);
- return;
- }
- resolve(createIterResult(undefined, true));
- });
- });
- }), _Object$setPrototypeO), AsyncIteratorPrototype);
- var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
- var _Object$create;
- var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
- value: stream,
- writable: true
- }), _defineProperty(_Object$create, kLastResolve, {
- value: null,
- writable: true
- }), _defineProperty(_Object$create, kLastReject, {
- value: null,
- writable: true
- }), _defineProperty(_Object$create, kError, {
- value: null,
- writable: true
- }), _defineProperty(_Object$create, kEnded, {
- value: stream._readableState.endEmitted,
- writable: true
- }), _defineProperty(_Object$create, kHandlePromise, {
- value: function value(resolve, reject) {
- var data = iterator[kStream].read();
- if (data) {
- iterator[kLastPromise] = null;
- iterator[kLastResolve] = null;
- iterator[kLastReject] = null;
- resolve(createIterResult(data, false));
- } else {
- iterator[kLastResolve] = resolve;
- iterator[kLastReject] = reject;
- }
- },
- writable: true
- }), _Object$create));
- iterator[kLastPromise] = null;
- finished(stream, function (err) {
- if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
- var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
- // returned by next() and store the error
- if (reject !== null) {
- iterator[kLastPromise] = null;
- iterator[kLastResolve] = null;
- iterator[kLastReject] = null;
- reject(err);
- }
- iterator[kError] = err;
- return;
- }
- var resolve = iterator[kLastResolve];
- if (resolve !== null) {
- iterator[kLastPromise] = null;
- iterator[kLastResolve] = null;
- iterator[kLastReject] = null;
- resolve(createIterResult(undefined, true));
- }
- iterator[kEnded] = true;
- });
- stream.on('readable', onReadable.bind(null, iterator));
- return iterator;
- };
- module.exports = createReadableStreamAsyncIterator;
- }).call(this,require('_process'))
- },{"./end-of-stream":349,"_process":312}],347:[function(require,module,exports){
- 'use strict';
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var _require = require('buffer'),
- Buffer = _require.Buffer;
- var _require2 = require('util'),
- inspect = _require2.inspect;
- var custom = inspect && inspect.custom || 'inspect';
- function copyBuffer(src, target, offset) {
- Buffer.prototype.copy.call(src, target, offset);
- }
- module.exports =
- /*#__PURE__*/
- function () {
- function BufferList() {
- this.head = null;
- this.tail = null;
- this.length = 0;
- }
- var _proto = BufferList.prototype;
- _proto.push = function push(v) {
- var entry = {
- data: v,
- next: null
- };
- if (this.length > 0) this.tail.next = entry;else this.head = entry;
- this.tail = entry;
- ++this.length;
- };
- _proto.unshift = function unshift(v) {
- var entry = {
- data: v,
- next: this.head
- };
- if (this.length === 0) this.tail = entry;
- this.head = entry;
- ++this.length;
- };
- _proto.shift = function shift() {
- if (this.length === 0) return;
- var ret = this.head.data;
- if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
- --this.length;
- return ret;
- };
- _proto.clear = function clear() {
- this.head = this.tail = null;
- this.length = 0;
- };
- _proto.join = function join(s) {
- if (this.length === 0) return '';
- var p = this.head;
- var ret = '' + p.data;
- while (p = p.next) {
- ret += s + p.data;
- }
- return ret;
- };
- _proto.concat = function concat(n) {
- if (this.length === 0) return Buffer.alloc(0);
- var ret = Buffer.allocUnsafe(n >>> 0);
- var p = this.head;
- var i = 0;
- while (p) {
- copyBuffer(p.data, ret, i);
- i += p.data.length;
- p = p.next;
- }
- return ret;
- } // Consumes a specified amount of bytes or characters from the buffered data.
- ;
- _proto.consume = function consume(n, hasStrings) {
- var ret;
- if (n < this.head.data.length) {
- // `slice` is the same for buffers and strings.
- ret = this.head.data.slice(0, n);
- this.head.data = this.head.data.slice(n);
- } else if (n === this.head.data.length) {
- // First chunk is a perfect match.
- ret = this.shift();
- } else {
- // Result spans more than one buffer.
- ret = hasStrings ? this._getString(n) : this._getBuffer(n);
- }
- return ret;
- };
- _proto.first = function first() {
- return this.head.data;
- } // Consumes a specified amount of characters from the buffered data.
- ;
- _proto._getString = function _getString(n) {
- var p = this.head;
- var c = 1;
- var ret = p.data;
- n -= ret.length;
- while (p = p.next) {
- var str = p.data;
- var nb = n > str.length ? str.length : n;
- if (nb === str.length) ret += str;else ret += str.slice(0, n);
- n -= nb;
- if (n === 0) {
- if (nb === str.length) {
- ++c;
- if (p.next) this.head = p.next;else this.head = this.tail = null;
- } else {
- this.head = p;
- p.data = str.slice(nb);
- }
- break;
- }
- ++c;
- }
- this.length -= c;
- return ret;
- } // Consumes a specified amount of bytes from the buffered data.
- ;
- _proto._getBuffer = function _getBuffer(n) {
- var ret = Buffer.allocUnsafe(n);
- var p = this.head;
- var c = 1;
- p.data.copy(ret);
- n -= p.data.length;
- while (p = p.next) {
- var buf = p.data;
- var nb = n > buf.length ? buf.length : n;
- buf.copy(ret, ret.length - n, 0, nb);
- n -= nb;
- if (n === 0) {
- if (nb === buf.length) {
- ++c;
- if (p.next) this.head = p.next;else this.head = this.tail = null;
- } else {
- this.head = p;
- p.data = buf.slice(nb);
- }
- break;
- }
- ++c;
- }
- this.length -= c;
- return ret;
- } // Make sure the linked list only shows the minimal necessary information.
- ;
- _proto[custom] = function (_, options) {
- return inspect(this, _objectSpread({}, options, {
- // Only inspect one level.
- depth: 0,
- // It should not recurse.
- customInspect: false
- }));
- };
- return BufferList;
- }();
- },{"buffer":47,"util":32}],348:[function(require,module,exports){
- (function (process){
- 'use strict'; // undocumented cb() API, needed for core, not for public API
- function destroy(err, cb) {
- var _this = this;
- var readableDestroyed = this._readableState && this._readableState.destroyed;
- var writableDestroyed = this._writableState && this._writableState.destroyed;
- if (readableDestroyed || writableDestroyed) {
- if (cb) {
- cb(err);
- } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
- process.nextTick(emitErrorNT, this, err);
- }
- return this;
- } // we set destroyed to true before firing error callbacks in order
- // to make it re-entrance safe in case destroy() is called within callbacks
- if (this._readableState) {
- this._readableState.destroyed = true;
- } // if this is a duplex stream mark the writable part as destroyed as well
- if (this._writableState) {
- this._writableState.destroyed = true;
- }
- this._destroy(err || null, function (err) {
- if (!cb && err) {
- process.nextTick(emitErrorAndCloseNT, _this, err);
- if (_this._writableState) {
- _this._writableState.errorEmitted = true;
- }
- } else if (cb) {
- process.nextTick(emitCloseNT, _this);
- cb(err);
- } else {
- process.nextTick(emitCloseNT, _this);
- }
- });
- return this;
- }
- function emitErrorAndCloseNT(self, err) {
- emitErrorNT(self, err);
- emitCloseNT(self);
- }
- function emitCloseNT(self) {
- if (self._writableState && !self._writableState.emitClose) return;
- if (self._readableState && !self._readableState.emitClose) return;
- self.emit('close');
- }
- function undestroy() {
- if (this._readableState) {
- this._readableState.destroyed = false;
- this._readableState.reading = false;
- this._readableState.ended = false;
- this._readableState.endEmitted = false;
- }
- if (this._writableState) {
- this._writableState.destroyed = false;
- this._writableState.ended = false;
- this._writableState.ending = false;
- this._writableState.finalCalled = false;
- this._writableState.prefinished = false;
- this._writableState.finished = false;
- this._writableState.errorEmitted = false;
- }
- }
- function emitErrorNT(self, err) {
- self.emit('error', err);
- }
- module.exports = {
- destroy: destroy,
- undestroy: undestroy
- };
- }).call(this,require('_process'))
- },{"_process":312}],349:[function(require,module,exports){
- // Ported from https://github.com/mafintosh/end-of-stream with
- // permission from the author, Mathias Buus (@mafintosh).
- 'use strict';
- var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
- function once(callback) {
- var called = false;
- return function () {
- if (called) return;
- called = true;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- callback.apply(this, args);
- };
- }
- function noop() {}
- function isRequest(stream) {
- return stream.setHeader && typeof stream.abort === 'function';
- }
- function eos(stream, opts, callback) {
- if (typeof opts === 'function') return eos(stream, null, opts);
- if (!opts) opts = {};
- callback = once(callback || noop);
- var readable = opts.readable || opts.readable !== false && stream.readable;
- var writable = opts.writable || opts.writable !== false && stream.writable;
- var onlegacyfinish = function onlegacyfinish() {
- if (!stream.writable) onfinish();
- };
- var writableEnded = stream._writableState && stream._writableState.finished;
- var onfinish = function onfinish() {
- writable = false;
- writableEnded = true;
- if (!readable) callback.call(stream);
- };
- var readableEnded = stream._readableState && stream._readableState.endEmitted;
- var onend = function onend() {
- readable = false;
- readableEnded = true;
- if (!writable) callback.call(stream);
- };
- var onerror = function onerror(err) {
- callback.call(stream, err);
- };
- var onclose = function onclose() {
- var err;
- if (readable && !readableEnded) {
- if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
- return callback.call(stream, err);
- }
- if (writable && !writableEnded) {
- if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
- return callback.call(stream, err);
- }
- };
- var onrequest = function onrequest() {
- stream.req.on('finish', onfinish);
- };
- if (isRequest(stream)) {
- stream.on('complete', onfinish);
- stream.on('abort', onclose);
- if (stream.req) onrequest();else stream.on('request', onrequest);
- } else if (writable && !stream._writableState) {
- // legacy streams
- stream.on('end', onlegacyfinish);
- stream.on('close', onlegacyfinish);
- }
- stream.on('end', onend);
- stream.on('finish', onfinish);
- if (opts.error !== false) stream.on('error', onerror);
- stream.on('close', onclose);
- return function () {
- stream.removeListener('complete', onfinish);
- stream.removeListener('abort', onclose);
- stream.removeListener('request', onrequest);
- if (stream.req) stream.req.removeListener('finish', onfinish);
- stream.removeListener('end', onlegacyfinish);
- stream.removeListener('close', onlegacyfinish);
- stream.removeListener('finish', onfinish);
- stream.removeListener('end', onend);
- stream.removeListener('error', onerror);
- stream.removeListener('close', onclose);
- };
- }
- module.exports = eos;
- },{"../../../errors":339}],350:[function(require,module,exports){
- // Ported from https://github.com/mafintosh/pump with
- // permission from the author, Mathias Buus (@mafintosh).
- 'use strict';
- var eos;
- function once(callback) {
- var called = false;
- return function () {
- if (called) return;
- called = true;
- callback.apply(void 0, arguments);
- };
- }
- var _require$codes = require('../../../errors').codes,
- ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
- ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
- function noop(err) {
- // Rethrow the error if it exists to avoid swallowing it
- if (err) throw err;
- }
- function isRequest(stream) {
- return stream.setHeader && typeof stream.abort === 'function';
- }
- function destroyer(stream, reading, writing, callback) {
- callback = once(callback);
- var closed = false;
- stream.on('close', function () {
- closed = true;
- });
- if (eos === undefined) eos = require('./end-of-stream');
- eos(stream, {
- readable: reading,
- writable: writing
- }, function (err) {
- if (err) return callback(err);
- closed = true;
- callback();
- });
- var destroyed = false;
- return function (err) {
- if (closed) return;
- if (destroyed) return;
- destroyed = true; // request.destroy just do .end - .abort is what we want
- if (isRequest(stream)) return stream.abort();
- if (typeof stream.destroy === 'function') return stream.destroy();
- callback(err || new ERR_STREAM_DESTROYED('pipe'));
- };
- }
- function call(fn) {
- fn();
- }
- function pipe(from, to) {
- return from.pipe(to);
- }
- function popCallback(streams) {
- if (!streams.length) return noop;
- if (typeof streams[streams.length - 1] !== 'function') return noop;
- return streams.pop();
- }
- function pipeline() {
- for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
- streams[_key] = arguments[_key];
- }
- var callback = popCallback(streams);
- if (Array.isArray(streams[0])) streams = streams[0];
- if (streams.length < 2) {
- throw new ERR_MISSING_ARGS('streams');
- }
- var error;
- var destroys = streams.map(function (stream, i) {
- var reading = i < streams.length - 1;
- var writing = i > 0;
- return destroyer(stream, reading, writing, function (err) {
- if (!error) error = err;
- if (err) destroys.forEach(call);
- if (reading) return;
- destroys.forEach(call);
- callback(error);
- });
- });
- return streams.reduce(pipe);
- }
- module.exports = pipeline;
- },{"../../../errors":339,"./end-of-stream":349}],351:[function(require,module,exports){
- 'use strict';
- var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
- function highWaterMarkFrom(options, isDuplex, duplexKey) {
- return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
- }
- function getHighWaterMark(state, options, duplexKey, isDuplex) {
- var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
- if (hwm != null) {
- if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
- var name = isDuplex ? duplexKey : 'highWaterMark';
- throw new ERR_INVALID_OPT_VALUE(name, hwm);
- }
- return Math.floor(hwm);
- } // Default value
- return state.objectMode ? 16 : 16 * 1024;
- }
- module.exports = {
- getHighWaterMark: getHighWaterMark
- };
- },{"../../../errors":339}],352:[function(require,module,exports){
- arguments[4][325][0].apply(exports,arguments)
- },{"dup":325,"events":239}],353:[function(require,module,exports){
- exports = module.exports = require('./lib/_stream_readable.js');
- exports.Stream = exports;
- exports.Readable = exports;
- exports.Writable = require('./lib/_stream_writable.js');
- exports.Duplex = require('./lib/_stream_duplex.js');
- exports.Transform = require('./lib/_stream_transform.js');
- exports.PassThrough = require('./lib/_stream_passthrough.js');
- exports.finished = require('./lib/internal/streams/end-of-stream.js');
- exports.pipeline = require('./lib/internal/streams/pipeline.js');
- },{"./lib/_stream_duplex.js":341,"./lib/_stream_passthrough.js":342,"./lib/_stream_readable.js":343,"./lib/_stream_transform.js":344,"./lib/_stream_writable.js":345,"./lib/internal/streams/end-of-stream.js":349,"./lib/internal/streams/pipeline.js":350}],354:[function(require,module,exports){
- arguments[4][327][0].apply(exports,arguments)
- },{"dup":327,"safe-buffer":333}],355:[function(require,module,exports){
- (function (setImmediate,clearImmediate){
- var nextTick = require('process/browser.js').nextTick;
- var apply = Function.prototype.apply;
- var slice = Array.prototype.slice;
- var immediateIds = {};
- var nextImmediateId = 0;
- // DOM APIs, for completeness
- exports.setTimeout = function() {
- return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
- };
- exports.setInterval = function() {
- return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
- };
- exports.clearTimeout =
- exports.clearInterval = function(timeout) { timeout.close(); };
- function Timeout(id, clearFn) {
- this._id = id;
- this._clearFn = clearFn;
- }
- Timeout.prototype.unref = Timeout.prototype.ref = function() {};
- Timeout.prototype.close = function() {
- this._clearFn.call(window, this._id);
- };
- // Does not start the time, just sets up the members needed.
- exports.enroll = function(item, msecs) {
- clearTimeout(item._idleTimeoutId);
- item._idleTimeout = msecs;
- };
- exports.unenroll = function(item) {
- clearTimeout(item._idleTimeoutId);
- item._idleTimeout = -1;
- };
- exports._unrefActive = exports.active = function(item) {
- clearTimeout(item._idleTimeoutId);
- var msecs = item._idleTimeout;
- if (msecs >= 0) {
- item._idleTimeoutId = setTimeout(function onTimeout() {
- if (item._onTimeout)
- item._onTimeout();
- }, msecs);
- }
- };
- // That's not how node.js implements it but the exposed api is the same.
- exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
- var id = nextImmediateId++;
- var args = arguments.length < 2 ? false : slice.call(arguments, 1);
- immediateIds[id] = true;
- nextTick(function onNextTick() {
- if (immediateIds[id]) {
- // fn.call() is faster so we optimize for the common use-case
- // @see http://jsperf.com/call-apply-segu
- if (args) {
- fn.apply(null, args);
- } else {
- fn.call(null);
- }
- // Prevent ids from leaking
- exports.clearImmediate(id);
- }
- });
- return id;
- };
- exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
- delete immediateIds[id];
- };
- }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
- },{"process/browser.js":312,"timers":355}],356:[function(require,module,exports){
- (function (process){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
- exports.clone = clone;
- exports.addLast = addLast;
- exports.addFirst = addFirst;
- exports.removeLast = removeLast;
- exports.removeFirst = removeFirst;
- exports.insert = insert;
- exports.removeAt = removeAt;
- exports.replaceAt = replaceAt;
- exports.getIn = getIn;
- exports.set = set;
- exports.setIn = setIn;
- exports.update = update;
- exports.updateIn = updateIn;
- exports.merge = merge;
- exports.mergeDeep = mergeDeep;
- exports.mergeIn = mergeIn;
- exports.omit = omit;
- exports.addDefaults = addDefaults;
- /*!
- * Timm
- *
- * Immutability helpers with fast reads and acceptable writes.
- *
- * @copyright Guillermo Grau Panea 2016
- * @license MIT
- */
- var INVALID_ARGS = 'INVALID_ARGS';
- // ===============================================
- // ### Helpers
- // ===============================================
- function throwStr(msg) {
- throw new Error(msg);
- }
- function getKeysAndSymbols(obj) {
- var keys = Object.keys(obj);
- if (Object.getOwnPropertySymbols) {
- return keys.concat(Object.getOwnPropertySymbols(obj));
- }
- return keys;
- }
- var hasOwnProperty = {}.hasOwnProperty;
- function clone(obj) {
- if (Array.isArray(obj)) return obj.slice();
- var keys = getKeysAndSymbols(obj);
- var out = {};
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- out[key] = obj[key];
- }
- return out;
- }
- function doMerge(fAddDefaults, fDeep, first) {
- var out = first;
- !(out != null) && throwStr(process.env.NODE_ENV !== 'production' ? 'At least one object should be provided to merge()' : INVALID_ARGS);
- var fChanged = false;
- for (var _len = arguments.length, rest = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
- rest[_key - 3] = arguments[_key];
- }
- for (var idx = 0; idx < rest.length; idx++) {
- var obj = rest[idx];
- if (obj == null) continue;
- var keys = getKeysAndSymbols(obj);
- if (!keys.length) continue;
- for (var j = 0; j <= keys.length; j++) {
- var key = keys[j];
- if (fAddDefaults && out[key] !== undefined) continue;
- var nextVal = obj[key];
- if (fDeep && isObject(out[key]) && isObject(nextVal)) {
- nextVal = doMerge(fAddDefaults, fDeep, out[key], nextVal);
- }
- if (nextVal === undefined || nextVal === out[key]) continue;
- if (!fChanged) {
- fChanged = true;
- out = clone(out);
- }
- out[key] = nextVal;
- }
- }
- return out;
- }
- function isObject(o) {
- var type = typeof o === 'undefined' ? 'undefined' : _typeof(o);
- return o != null && type === 'object';
- }
- // _deepFreeze = (obj) ->
- // Object.freeze obj
- // for key in Object.getOwnPropertyNames obj
- // val = obj[key]
- // if isObject(val) and not Object.isFrozen val
- // _deepFreeze val
- // obj
- // ===============================================
- // -- ### Arrays
- // ===============================================
- // -- #### addLast()
- // -- Returns a new array with an appended item or items.
- // --
- // -- Usage: `addLast<T>(array: Array<T>, val: Array<T>|T): Array<T>`
- // --
- // -- ```js
- // -- arr = ['a', 'b']
- // -- arr2 = addLast(arr, 'c')
- // -- // ['a', 'b', 'c']
- // -- arr2 === arr
- // -- // false
- // -- arr3 = addLast(arr, ['c', 'd'])
- // -- // ['a', 'b', 'c', 'd']
- // -- ```
- // `array.concat(val)` also handles the scalar case,
- // but is apparently very slow
- function addLast(array, val) {
- if (Array.isArray(val)) return array.concat(val);
- return array.concat([val]);
- }
- // -- #### addFirst()
- // -- Returns a new array with a prepended item or items.
- // --
- // -- Usage: `addFirst<T>(array: Array<T>, val: Array<T>|T): Array<T>`
- // --
- // -- ```js
- // -- arr = ['a', 'b']
- // -- arr2 = addFirst(arr, 'c')
- // -- // ['c', 'a', 'b']
- // -- arr2 === arr
- // -- // false
- // -- arr3 = addFirst(arr, ['c', 'd'])
- // -- // ['c', 'd', 'a', 'b']
- // -- ```
- function addFirst(array, val) {
- if (Array.isArray(val)) return val.concat(array);
- return [val].concat(array);
- }
- // -- #### removeLast()
- // -- Returns a new array removing the last item.
- // --
- // -- Usage: `removeLast<T>(array: Array<T>): Array<T>`
- // --
- // -- ```js
- // -- arr = ['a', 'b']
- // -- arr2 = removeLast(arr)
- // -- // ['a']
- // -- arr2 === arr
- // -- // false
- // --
- // -- // The same array is returned if there are no changes:
- // -- arr3 = []
- // -- removeLast(arr3) === arr3
- // -- // true
- // -- ```
- function removeLast(array) {
- if (!array.length) return array;
- return array.slice(0, array.length - 1);
- }
- // -- #### removeFirst()
- // -- Returns a new array removing the first item.
- // --
- // -- Usage: `removeFirst<T>(array: Array<T>): Array<T>`
- // --
- // -- ```js
- // -- arr = ['a', 'b']
- // -- arr2 = removeFirst(arr)
- // -- // ['b']
- // -- arr2 === arr
- // -- // false
- // --
- // -- // The same array is returned if there are no changes:
- // -- arr3 = []
- // -- removeFirst(arr3) === arr3
- // -- // true
- // -- ```
- function removeFirst(array) {
- if (!array.length) return array;
- return array.slice(1);
- }
- // -- #### insert()
- // -- Returns a new array obtained by inserting an item or items
- // -- at a specified index.
- // --
- // -- Usage: `insert<T>(array: Array<T>, idx: number, val: Array<T>|T): Array<T>`
- // --
- // -- ```js
- // -- arr = ['a', 'b', 'c']
- // -- arr2 = insert(arr, 1, 'd')
- // -- // ['a', 'd', 'b', 'c']
- // -- arr2 === arr
- // -- // false
- // -- insert(arr, 1, ['d', 'e'])
- // -- // ['a', 'd', 'e', 'b', 'c']
- // -- ```
- function insert(array, idx, val) {
- return array.slice(0, idx).concat(Array.isArray(val) ? val : [val]).concat(array.slice(idx));
- }
- // -- #### removeAt()
- // -- Returns a new array obtained by removing an item at
- // -- a specified index.
- // --
- // -- Usage: `removeAt<T>(array: Array<T>, idx: number): Array<T>`
- // --
- // -- ```js
- // -- arr = ['a', 'b', 'c']
- // -- arr2 = removeAt(arr, 1)
- // -- // ['a', 'c']
- // -- arr2 === arr
- // -- // false
- // --
- // -- // The same array is returned if there are no changes:
- // -- removeAt(arr, 4) === arr
- // -- // true
- // -- ```
- function removeAt(array, idx) {
- if (idx >= array.length || idx < 0) return array;
- return array.slice(0, idx).concat(array.slice(idx + 1));
- }
- // -- #### replaceAt()
- // -- Returns a new array obtained by replacing an item at
- // -- a specified index. If the provided item is the same as
- // -- (*referentially equal to*) the previous item at that position,
- // -- the original array is returned.
- // --
- // -- Usage: `replaceAt<T>(array: Array<T>, idx: number, newItem: T): Array<T>`
- // --
- // -- ```js
- // -- arr = ['a', 'b', 'c']
- // -- arr2 = replaceAt(arr, 1, 'd')
- // -- // ['a', 'd', 'c']
- // -- arr2 === arr
- // -- // false
- // --
- // -- // The same object is returned if there are no changes:
- // -- replaceAt(arr, 1, 'b') === arr
- // -- // true
- // -- ```
- function replaceAt(array, idx, newItem) {
- if (array[idx] === newItem) return array;
- var len = array.length;
- var result = Array(len);
- for (var i = 0; i < len; i++) {
- result[i] = array[i];
- }
- result[idx] = newItem;
- return result;
- }
- // ===============================================
- // -- ### Collections (objects and arrays)
- // ===============================================
- // -- The following types are used throughout this section
- // -- ```js
- // -- type ArrayOrObject = Array<any>|Object;
- // -- type Key = number|string;
- // -- ```
- // -- #### getIn()
- // -- Returns a value from an object at a given path. Works with
- // -- nested arrays and objects. If the path does not exist, it returns
- // -- `undefined`.
- // --
- // -- Usage: `getIn(obj: ?ArrayOrObject, path: Array<Key>): any`
- // --
- // -- ```js
- // -- obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: ['a', 'b', 'c'] }
- // -- getIn(obj, ['d', 'd1'])
- // -- // 3
- // -- getIn(obj, ['e', 1])
- // -- // 'b'
- // -- ```
- function getIn(obj, path) {
- !Array.isArray(path) && throwStr(process.env.NODE_ENV !== 'production' ? 'A path array should be provided when calling getIn()' : INVALID_ARGS);
- if (obj == null) return undefined;
- var ptr = obj;
- for (var i = 0; i < path.length; i++) {
- var key = path[i];
- ptr = ptr != null ? ptr[key] : undefined;
- if (ptr === undefined) return ptr;
- }
- return ptr;
- }
- // -- #### set()
- // -- Returns a new object with a modified attribute.
- // -- If the provided value is the same as (*referentially equal to*)
- // -- the previous value, the original object is returned.
- // --
- // -- Usage: `set<T>(obj: ?T, key: Key, val: any): T`
- // --
- // -- ```js
- // -- obj = { a: 1, b: 2, c: 3 }
- // -- obj2 = set(obj, 'b', 5)
- // -- // { a: 1, b: 5, c: 3 }
- // -- obj2 === obj
- // -- // false
- // --
- // -- // The same object is returned if there are no changes:
- // -- set(obj, 'b', 2) === obj
- // -- // true
- // -- ```
- function set(obj, key, val) {
- var fallback = typeof key === 'number' ? [] : {};
- var finalObj = obj == null ? fallback : obj;
- if (finalObj[key] === val) return finalObj;
- var obj2 = clone(finalObj);
- obj2[key] = val;
- return obj2;
- }
- // -- #### setIn()
- // -- Returns a new object with a modified **nested** attribute.
- // --
- // -- Notes:
- // --
- // -- * If the provided value is the same as (*referentially equal to*)
- // -- the previous value, the original object is returned.
- // -- * If the path does not exist, it will be created before setting
- // -- the new value.
- // --
- // -- Usage: `setIn<T: ArrayOrObject>(obj: T, path: Array<Key>, val: any): T`
- // --
- // -- ```js
- // -- obj = { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } }
- // -- obj2 = setIn(obj, ['d', 'd1'], 4)
- // -- // { a: 1, b: 2, d: { d1: 4, d2: 4 }, e: { e1: 'foo', e2: 'bar' } }
- // -- obj2 === obj
- // -- // false
- // -- obj2.d === obj.d
- // -- // false
- // -- obj2.e === obj.e
- // -- // true
- // --
- // -- // The same object is returned if there are no changes:
- // -- obj3 = setIn(obj, ['d', 'd1'], 3)
- // -- // { a: 1, b: 2, d: { d1: 3, d2: 4 }, e: { e1: 'foo', e2: 'bar' } }
- // -- obj3 === obj
- // -- // true
- // -- obj3.d === obj.d
- // -- // true
- // -- obj3.e === obj.e
- // -- // true
- // --
- // -- // ... unknown paths create intermediate keys. Numeric segments are treated as array indices:
- // -- setIn({ a: 3 }, ['unknown', 0, 'path'], 4)
- // -- // { a: 3, unknown: [{ path: 4 }] }
- // -- ```
- function doSetIn(obj, path, val, idx) {
- var newValue = void 0;
- var key = path[idx];
- if (idx === path.length - 1) {
- newValue = val;
- } else {
- var nestedObj = isObject(obj) && isObject(obj[key]) ? obj[key] : typeof path[idx + 1] === 'number' ? [] : {};
- newValue = doSetIn(nestedObj, path, val, idx + 1);
- }
- return set(obj, key, newValue);
- }
- function setIn(obj, path, val) {
- if (!path.length) return val;
- return doSetIn(obj, path, val, 0);
- }
- // -- #### update()
- // -- Returns a new object with a modified attribute,
- // -- calculated via a user-provided callback based on the current value.
- // -- If the calculated value is the same as (*referentially equal to*)
- // -- the previous value, the original object is returned.
- // --
- // -- Usage: `update<T: ArrayOrObject>(obj: T, key: Key,
- // -- fnUpdate: (prevValue: any) => any): T`
- // --
- // -- ```js
- // -- obj = { a: 1, b: 2, c: 3 }
- // -- obj2 = update(obj, 'b', (val) => val + 1)
- // -- // { a: 1, b: 3, c: 3 }
- // -- obj2 === obj
- // -- // false
- // --
- // -- // The same object is returned if there are no changes:
- // -- update(obj, 'b', (val) => val) === obj
- // -- // true
- // -- ```
- function update(obj, key, fnUpdate) {
- var prevVal = obj == null ? undefined : obj[key];
- var nextVal = fnUpdate(prevVal);
- return set(obj, key, nextVal);
- }
- // -- #### updateIn()
- // -- Returns a new object with a modified **nested** attribute,
- // -- calculated via a user-provided callback based on the current value.
- // -- If the calculated value is the same as (*referentially equal to*)
- // -- the previous value, the original object is returned.
- // --
- // -- Usage: `updateIn<T: ArrayOrObject>(obj: T, path: Array<Key>,
- // -- fnUpdate: (prevValue: any) => any): T`
- // --
- // -- ```js
- // -- obj = { a: 1, d: { d1: 3, d2: 4 } }
- // -- obj2 = updateIn(obj, ['d', 'd1'], (val) => val + 1)
- // -- // { a: 1, d: { d1: 4, d2: 4 } }
- // -- obj2 === obj
- // -- // false
- // --
- // -- // The same object is returned if there are no changes:
- // -- obj3 = updateIn(obj, ['d', 'd1'], (val) => val)
- // -- // { a: 1, d: { d1: 3, d2: 4 } }
- // -- obj3 === obj
- // -- // true
- // -- ```
- function updateIn(obj, path, fnUpdate) {
- var prevVal = getIn(obj, path);
- var nextVal = fnUpdate(prevVal);
- return setIn(obj, path, nextVal);
- }
- // -- #### merge()
- // -- Returns a new object built as follows: the overlapping keys from the
- // -- second one overwrite the corresponding entries from the first one.
- // -- Similar to `Object.assign()`, but immutable.
- // --
- // -- Usage:
- // --
- // -- * `merge(obj1: Object, obj2: ?Object): Object`
- // -- * `merge(obj1: Object, ...objects: Array<?Object>): Object`
- // --
- // -- The unmodified `obj1` is returned if `obj2` does not *provide something
- // -- new to* `obj1`, i.e. if either of the following
- // -- conditions are true:
- // --
- // -- * `obj2` is `null` or `undefined`
- // -- * `obj2` is an object, but it is empty
- // -- * All attributes of `obj2` are `undefined`
- // -- * All attributes of `obj2` are referentially equal to the
- // -- corresponding attributes of `obj1`
- // --
- // -- Note that `undefined` attributes in `obj2` do not modify the
- // -- corresponding attributes in `obj1`.
- // --
- // -- ```js
- // -- obj1 = { a: 1, b: 2, c: 3 }
- // -- obj2 = { c: 4, d: 5 }
- // -- obj3 = merge(obj1, obj2)
- // -- // { a: 1, b: 2, c: 4, d: 5 }
- // -- obj3 === obj1
- // -- // false
- // --
- // -- // The same object is returned if there are no changes:
- // -- merge(obj1, { c: 3 }) === obj1
- // -- // true
- // -- ```
- function merge(a, b, c, d, e, f) {
- for (var _len2 = arguments.length, rest = Array(_len2 > 6 ? _len2 - 6 : 0), _key2 = 6; _key2 < _len2; _key2++) {
- rest[_key2 - 6] = arguments[_key2];
- }
- return rest.length ? doMerge.call.apply(doMerge, [null, false, false, a, b, c, d, e, f].concat(rest)) : doMerge(false, false, a, b, c, d, e, f);
- }
- // -- #### mergeDeep()
- // -- Returns a new object built as follows: the overlapping keys from the
- // -- second one overwrite the corresponding entries from the first one.
- // -- If both the first and second entries are objects they are merged recursively.
- // -- Similar to `Object.assign()`, but immutable, and deeply merging.
- // --
- // -- Usage:
- // --
- // -- * `mergeDeep(obj1: Object, obj2: ?Object): Object`
- // -- * `mergeDeep(obj1: Object, ...objects: Array<?Object>): Object`
- // --
- // -- The unmodified `obj1` is returned if `obj2` does not *provide something
- // -- new to* `obj1`, i.e. if either of the following
- // -- conditions are true:
- // --
- // -- * `obj2` is `null` or `undefined`
- // -- * `obj2` is an object, but it is empty
- // -- * All attributes of `obj2` are `undefined`
- // -- * All attributes of `obj2` are referentially equal to the
- // -- corresponding attributes of `obj1`
- // --
- // -- Note that `undefined` attributes in `obj2` do not modify the
- // -- corresponding attributes in `obj1`.
- // --
- // -- ```js
- // -- obj1 = { a: 1, b: 2, c: { a: 1 } }
- // -- obj2 = { b: 3, c: { b: 2 } }
- // -- obj3 = mergeDeep(obj1, obj2)
- // -- // { a: 1, b: 3, c: { a: 1, b: 2 } }
- // -- obj3 === obj1
- // -- // false
- // --
- // -- // The same object is returned if there are no changes:
- // -- mergeDeep(obj1, { c: { a: 1 } }) === obj1
- // -- // true
- // -- ```
- function mergeDeep(a, b, c, d, e, f) {
- for (var _len3 = arguments.length, rest = Array(_len3 > 6 ? _len3 - 6 : 0), _key3 = 6; _key3 < _len3; _key3++) {
- rest[_key3 - 6] = arguments[_key3];
- }
- return rest.length ? doMerge.call.apply(doMerge, [null, false, true, a, b, c, d, e, f].concat(rest)) : doMerge(false, true, a, b, c, d, e, f);
- }
- // -- #### mergeIn()
- // -- Similar to `merge()`, but merging the value at a given nested path.
- // -- Note that the returned type is the same as that of the first argument.
- // --
- // -- Usage:
- // --
- // -- * `mergeIn<T: ArrayOrObject>(obj1: T, path: Array<Key>, obj2: ?Object): T`
- // -- * `mergeIn<T: ArrayOrObject>(obj1: T, path: Array<Key>,
- // -- ...objects: Array<?Object>): T`
- // --
- // -- ```js
- // -- obj1 = { a: 1, d: { b: { d1: 3, d2: 4 } } }
- // -- obj2 = { d3: 5 }
- // -- obj3 = mergeIn(obj1, ['d', 'b'], obj2)
- // -- // { a: 1, d: { b: { d1: 3, d2: 4, d3: 5 } } }
- // -- obj3 === obj1
- // -- // false
- // --
- // -- // The same object is returned if there are no changes:
- // -- mergeIn(obj1, ['d', 'b'], { d2: 4 }) === obj1
- // -- // true
- // -- ```
- function mergeIn(a, path, b, c, d, e, f) {
- var prevVal = getIn(a, path);
- if (prevVal == null) prevVal = {};
- var nextVal = void 0;
- for (var _len4 = arguments.length, rest = Array(_len4 > 7 ? _len4 - 7 : 0), _key4 = 7; _key4 < _len4; _key4++) {
- rest[_key4 - 7] = arguments[_key4];
- }
- if (rest.length) {
- nextVal = doMerge.call.apply(doMerge, [null, false, false, prevVal, b, c, d, e, f].concat(rest));
- } else {
- nextVal = doMerge(false, false, prevVal, b, c, d, e, f);
- }
- return setIn(a, path, nextVal);
- }
- // -- #### omit()
- // -- Returns an object excluding one or several attributes.
- // --
- // -- Usage: `omit(obj: Object, attrs: Array<string>|string): Object`
- //
- // -- ```js
- // -- obj = { a: 1, b: 2, c: 3, d: 4 }
- // -- omit(obj, 'a')
- // -- // { b: 2, c: 3, d: 4 }
- // -- omit(obj, ['b', 'c'])
- // -- // { a: 1, d: 4 }
- // --
- // -- // The same object is returned if there are no changes:
- // -- omit(obj, 'z') === obj1
- // -- // true
- // -- ```
- function omit(obj, attrs) {
- var omitList = Array.isArray(attrs) ? attrs : [attrs];
- var fDoSomething = false;
- for (var i = 0; i < omitList.length; i++) {
- if (hasOwnProperty.call(obj, omitList[i])) {
- fDoSomething = true;
- break;
- }
- }
- if (!fDoSomething) return obj;
- var out = {};
- var keys = getKeysAndSymbols(obj);
- for (var _i = 0; _i < keys.length; _i++) {
- var key = keys[_i];
- if (omitList.indexOf(key) >= 0) continue;
- out[key] = obj[key];
- }
- return out;
- }
- // -- #### addDefaults()
- // -- Returns a new object built as follows: `undefined` keys in the first one
- // -- are filled in with the corresponding values from the second one
- // -- (even if they are `null`).
- // --
- // -- Usage:
- // --
- // -- * `addDefaults(obj: Object, defaults: Object): Object`
- // -- * `addDefaults(obj: Object, ...defaultObjects: Array<?Object>): Object`
- // --
- // -- ```js
- // -- obj1 = { a: 1, b: 2, c: 3 }
- // -- obj2 = { c: 4, d: 5, e: null }
- // -- obj3 = addDefaults(obj1, obj2)
- // -- // { a: 1, b: 2, c: 3, d: 5, e: null }
- // -- obj3 === obj1
- // -- // false
- // --
- // -- // The same object is returned if there are no changes:
- // -- addDefaults(obj1, { c: 4 }) === obj1
- // -- // true
- // -- ```
- function addDefaults(a, b, c, d, e, f) {
- for (var _len5 = arguments.length, rest = Array(_len5 > 6 ? _len5 - 6 : 0), _key5 = 6; _key5 < _len5; _key5++) {
- rest[_key5 - 6] = arguments[_key5];
- }
- return rest.length ? doMerge.call.apply(doMerge, [null, true, false, a, b, c, d, e, f].concat(rest)) : doMerge(true, false, a, b, c, d, e, f);
- }
- // ===============================================
- // ### Public API
- // ===============================================
- var timm = {
- clone: clone,
- addLast: addLast,
- addFirst: addFirst,
- removeLast: removeLast,
- removeFirst: removeFirst,
- insert: insert,
- removeAt: removeAt,
- replaceAt: replaceAt,
- getIn: getIn,
- // eslint-disable-next-line object-shorthand
- set: set, // so that flow doesn't complain
- setIn: setIn,
- update: update,
- updateIn: updateIn,
- merge: merge,
- mergeDeep: mergeDeep,
- mergeIn: mergeIn,
- omit: omit,
- addDefaults: addDefaults
- };
- exports.default = timm;
- }).call(this,require('_process'))
- },{"_process":312}],357:[function(require,module,exports){
- // TinyColor v1.4.1
- // https://github.com/bgrins/TinyColor
- // Brian Grinstead, MIT License
- (function(Math) {
- var trimLeft = /^\s+/,
- trimRight = /\s+$/,
- tinyCounter = 0,
- mathRound = Math.round,
- mathMin = Math.min,
- mathMax = Math.max,
- mathRandom = Math.random;
- function tinycolor (color, opts) {
- color = (color) ? color : '';
- opts = opts || { };
- // If input is already a tinycolor, return itself
- if (color instanceof tinycolor) {
- return color;
- }
- // If we are called as a function, call using new instead
- if (!(this instanceof tinycolor)) {
- return new tinycolor(color, opts);
- }
- var rgb = inputToRGB(color);
- this._originalInput = color,
- this._r = rgb.r,
- this._g = rgb.g,
- this._b = rgb.b,
- this._a = rgb.a,
- this._roundA = mathRound(100*this._a) / 100,
- this._format = opts.format || rgb.format;
- this._gradientType = opts.gradientType;
- // Don't let the range of [0,255] come back in [0,1].
- // Potentially lose a little bit of precision here, but will fix issues where
- // .5 gets interpreted as half of the total, instead of half of 1
- // If it was supposed to be 128, this was already taken care of by `inputToRgb`
- if (this._r < 1) { this._r = mathRound(this._r); }
- if (this._g < 1) { this._g = mathRound(this._g); }
- if (this._b < 1) { this._b = mathRound(this._b); }
- this._ok = rgb.ok;
- this._tc_id = tinyCounter++;
- }
- tinycolor.prototype = {
- isDark: function() {
- return this.getBrightness() < 128;
- },
- isLight: function() {
- return !this.isDark();
- },
- isValid: function() {
- return this._ok;
- },
- getOriginalInput: function() {
- return this._originalInput;
- },
- getFormat: function() {
- return this._format;
- },
- getAlpha: function() {
- return this._a;
- },
- getBrightness: function() {
- //http://www.w3.org/TR/AERT#color-contrast
- var rgb = this.toRgb();
- return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
- },
- getLuminance: function() {
- //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
- var rgb = this.toRgb();
- var RsRGB, GsRGB, BsRGB, R, G, B;
- RsRGB = rgb.r/255;
- GsRGB = rgb.g/255;
- BsRGB = rgb.b/255;
- if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
- if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
- if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
- return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
- },
- setAlpha: function(value) {
- this._a = boundAlpha(value);
- this._roundA = mathRound(100*this._a) / 100;
- return this;
- },
- toHsv: function() {
- var hsv = rgbToHsv(this._r, this._g, this._b);
- return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
- },
- toHsvString: function() {
- var hsv = rgbToHsv(this._r, this._g, this._b);
- var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
- return (this._a == 1) ?
- "hsv(" + h + ", " + s + "%, " + v + "%)" :
- "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
- },
- toHsl: function() {
- var hsl = rgbToHsl(this._r, this._g, this._b);
- return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
- },
- toHslString: function() {
- var hsl = rgbToHsl(this._r, this._g, this._b);
- var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
- return (this._a == 1) ?
- "hsl(" + h + ", " + s + "%, " + l + "%)" :
- "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
- },
- toHex: function(allow3Char) {
- return rgbToHex(this._r, this._g, this._b, allow3Char);
- },
- toHexString: function(allow3Char) {
- return '#' + this.toHex(allow3Char);
- },
- toHex8: function(allow4Char) {
- return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
- },
- toHex8String: function(allow4Char) {
- return '#' + this.toHex8(allow4Char);
- },
- toRgb: function() {
- return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
- },
- toRgbString: function() {
- return (this._a == 1) ?
- "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
- "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
- },
- toPercentageRgb: function() {
- return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
- },
- toPercentageRgbString: function() {
- return (this._a == 1) ?
- "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
- "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
- },
- toName: function() {
- if (this._a === 0) {
- return "transparent";
- }
- if (this._a < 1) {
- return false;
- }
- return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
- },
- toFilter: function(secondColor) {
- var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
- var secondHex8String = hex8String;
- var gradientType = this._gradientType ? "GradientType = 1, " : "";
- if (secondColor) {
- var s = tinycolor(secondColor);
- secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
- }
- return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
- },
- toString: function(format) {
- var formatSet = !!format;
- format = format || this._format;
- var formattedString = false;
- var hasAlpha = this._a < 1 && this._a >= 0;
- var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");
- if (needsAlphaFormat) {
- // Special case for "transparent", all other non-alpha formats
- // will return rgba when there is transparency.
- if (format === "name" && this._a === 0) {
- return this.toName();
- }
- return this.toRgbString();
- }
- if (format === "rgb") {
- formattedString = this.toRgbString();
- }
- if (format === "prgb") {
- formattedString = this.toPercentageRgbString();
- }
- if (format === "hex" || format === "hex6") {
- formattedString = this.toHexString();
- }
- if (format === "hex3") {
- formattedString = this.toHexString(true);
- }
- if (format === "hex4") {
- formattedString = this.toHex8String(true);
- }
- if (format === "hex8") {
- formattedString = this.toHex8String();
- }
- if (format === "name") {
- formattedString = this.toName();
- }
- if (format === "hsl") {
- formattedString = this.toHslString();
- }
- if (format === "hsv") {
- formattedString = this.toHsvString();
- }
- return formattedString || this.toHexString();
- },
- clone: function() {
- return tinycolor(this.toString());
- },
- _applyModification: function(fn, args) {
- var color = fn.apply(null, [this].concat([].slice.call(args)));
- this._r = color._r;
- this._g = color._g;
- this._b = color._b;
- this.setAlpha(color._a);
- return this;
- },
- lighten: function() {
- return this._applyModification(lighten, arguments);
- },
- brighten: function() {
- return this._applyModification(brighten, arguments);
- },
- darken: function() {
- return this._applyModification(darken, arguments);
- },
- desaturate: function() {
- return this._applyModification(desaturate, arguments);
- },
- saturate: function() {
- return this._applyModification(saturate, arguments);
- },
- greyscale: function() {
- return this._applyModification(greyscale, arguments);
- },
- spin: function() {
- return this._applyModification(spin, arguments);
- },
- _applyCombination: function(fn, args) {
- return fn.apply(null, [this].concat([].slice.call(args)));
- },
- analogous: function() {
- return this._applyCombination(analogous, arguments);
- },
- complement: function() {
- return this._applyCombination(complement, arguments);
- },
- monochromatic: function() {
- return this._applyCombination(monochromatic, arguments);
- },
- splitcomplement: function() {
- return this._applyCombination(splitcomplement, arguments);
- },
- triad: function() {
- return this._applyCombination(triad, arguments);
- },
- tetrad: function() {
- return this._applyCombination(tetrad, arguments);
- }
- };
- // If input is an object, force 1 into "1.0" to handle ratios properly
- // String input requires "1.0" as input, so 1 will be treated as 1
- tinycolor.fromRatio = function(color, opts) {
- if (typeof color == "object") {
- var newColor = {};
- for (var i in color) {
- if (color.hasOwnProperty(i)) {
- if (i === "a") {
- newColor[i] = color[i];
- }
- else {
- newColor[i] = convertToPercentage(color[i]);
- }
- }
- }
- color = newColor;
- }
- return tinycolor(color, opts);
- };
- // Given a string or object, convert that input to RGB
- // Possible string inputs:
- //
- // "red"
- // "#f00" or "f00"
- // "#ff0000" or "ff0000"
- // "#ff000000" or "ff000000"
- // "rgb 255 0 0" or "rgb (255, 0, 0)"
- // "rgb 1.0 0 0" or "rgb (1, 0, 0)"
- // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
- // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
- // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
- // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
- // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
- //
- function inputToRGB(color) {
- var rgb = { r: 0, g: 0, b: 0 };
- var a = 1;
- var s = null;
- var v = null;
- var l = null;
- var ok = false;
- var format = false;
- if (typeof color == "string") {
- color = stringInputToObject(color);
- }
- if (typeof color == "object") {
- if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
- rgb = rgbToRgb(color.r, color.g, color.b);
- ok = true;
- format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
- }
- else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
- s = convertToPercentage(color.s);
- v = convertToPercentage(color.v);
- rgb = hsvToRgb(color.h, s, v);
- ok = true;
- format = "hsv";
- }
- else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
- s = convertToPercentage(color.s);
- l = convertToPercentage(color.l);
- rgb = hslToRgb(color.h, s, l);
- ok = true;
- format = "hsl";
- }
- if (color.hasOwnProperty("a")) {
- a = color.a;
- }
- }
- a = boundAlpha(a);
- return {
- ok: ok,
- format: color.format || format,
- r: mathMin(255, mathMax(rgb.r, 0)),
- g: mathMin(255, mathMax(rgb.g, 0)),
- b: mathMin(255, mathMax(rgb.b, 0)),
- a: a
- };
- }
- // Conversion Functions
- // --------------------
- // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
- // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
- // `rgbToRgb`
- // Handle bounds / percentage checking to conform to CSS color spec
- // <http://www.w3.org/TR/css3-color/>
- // *Assumes:* r, g, b in [0, 255] or [0, 1]
- // *Returns:* { r, g, b } in [0, 255]
- function rgbToRgb(r, g, b){
- return {
- r: bound01(r, 255) * 255,
- g: bound01(g, 255) * 255,
- b: bound01(b, 255) * 255
- };
- }
- // `rgbToHsl`
- // Converts an RGB color value to HSL.
- // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
- // *Returns:* { h, s, l } in [0,1]
- function rgbToHsl(r, g, b) {
- r = bound01(r, 255);
- g = bound01(g, 255);
- b = bound01(b, 255);
- var max = mathMax(r, g, b), min = mathMin(r, g, b);
- var h, s, l = (max + min) / 2;
- if(max == min) {
- h = s = 0; // achromatic
- }
- else {
- var d = max - min;
- s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
- switch(max) {
- case r: h = (g - b) / d + (g < b ? 6 : 0); break;
- case g: h = (b - r) / d + 2; break;
- case b: h = (r - g) / d + 4; break;
- }
- h /= 6;
- }
- return { h: h, s: s, l: l };
- }
- // `hslToRgb`
- // Converts an HSL color value to RGB.
- // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
- // *Returns:* { r, g, b } in the set [0, 255]
- function hslToRgb(h, s, l) {
- var r, g, b;
- h = bound01(h, 360);
- s = bound01(s, 100);
- l = bound01(l, 100);
- function hue2rgb(p, q, t) {
- if(t < 0) t += 1;
- if(t > 1) t -= 1;
- if(t < 1/6) return p + (q - p) * 6 * t;
- if(t < 1/2) return q;
- if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
- return p;
- }
- if(s === 0) {
- r = g = b = l; // achromatic
- }
- else {
- var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
- var p = 2 * l - q;
- r = hue2rgb(p, q, h + 1/3);
- g = hue2rgb(p, q, h);
- b = hue2rgb(p, q, h - 1/3);
- }
- return { r: r * 255, g: g * 255, b: b * 255 };
- }
- // `rgbToHsv`
- // Converts an RGB color value to HSV
- // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
- // *Returns:* { h, s, v } in [0,1]
- function rgbToHsv(r, g, b) {
- r = bound01(r, 255);
- g = bound01(g, 255);
- b = bound01(b, 255);
- var max = mathMax(r, g, b), min = mathMin(r, g, b);
- var h, s, v = max;
- var d = max - min;
- s = max === 0 ? 0 : d / max;
- if(max == min) {
- h = 0; // achromatic
- }
- else {
- switch(max) {
- case r: h = (g - b) / d + (g < b ? 6 : 0); break;
- case g: h = (b - r) / d + 2; break;
- case b: h = (r - g) / d + 4; break;
- }
- h /= 6;
- }
- return { h: h, s: s, v: v };
- }
- // `hsvToRgb`
- // Converts an HSV color value to RGB.
- // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
- // *Returns:* { r, g, b } in the set [0, 255]
- function hsvToRgb(h, s, v) {
- h = bound01(h, 360) * 6;
- s = bound01(s, 100);
- v = bound01(v, 100);
- var i = Math.floor(h),
- f = h - i,
- p = v * (1 - s),
- q = v * (1 - f * s),
- t = v * (1 - (1 - f) * s),
- mod = i % 6,
- r = [v, q, p, p, t, v][mod],
- g = [t, v, v, q, p, p][mod],
- b = [p, p, t, v, v, q][mod];
- return { r: r * 255, g: g * 255, b: b * 255 };
- }
- // `rgbToHex`
- // Converts an RGB color to hex
- // Assumes r, g, and b are contained in the set [0, 255]
- // Returns a 3 or 6 character hex
- function rgbToHex(r, g, b, allow3Char) {
- var hex = [
- pad2(mathRound(r).toString(16)),
- pad2(mathRound(g).toString(16)),
- pad2(mathRound(b).toString(16))
- ];
- // Return a 3 character hex if possible
- if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
- return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
- }
- return hex.join("");
- }
- // `rgbaToHex`
- // Converts an RGBA color plus alpha transparency to hex
- // Assumes r, g, b are contained in the set [0, 255] and
- // a in [0, 1]. Returns a 4 or 8 character rgba hex
- function rgbaToHex(r, g, b, a, allow4Char) {
- var hex = [
- pad2(mathRound(r).toString(16)),
- pad2(mathRound(g).toString(16)),
- pad2(mathRound(b).toString(16)),
- pad2(convertDecimalToHex(a))
- ];
- // Return a 4 character hex if possible
- if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
- return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
- }
- return hex.join("");
- }
- // `rgbaToArgbHex`
- // Converts an RGBA color to an ARGB Hex8 string
- // Rarely used, but required for "toFilter()"
- function rgbaToArgbHex(r, g, b, a) {
- var hex = [
- pad2(convertDecimalToHex(a)),
- pad2(mathRound(r).toString(16)),
- pad2(mathRound(g).toString(16)),
- pad2(mathRound(b).toString(16))
- ];
- return hex.join("");
- }
- // `equals`
- // Can be called with any tinycolor input
- tinycolor.equals = function (color1, color2) {
- if (!color1 || !color2) { return false; }
- return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
- };
- tinycolor.random = function() {
- return tinycolor.fromRatio({
- r: mathRandom(),
- g: mathRandom(),
- b: mathRandom()
- });
- };
- // Modification Functions
- // ----------------------
- // Thanks to less.js for some of the basics here
- // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
- function desaturate(color, amount) {
- amount = (amount === 0) ? 0 : (amount || 10);
- var hsl = tinycolor(color).toHsl();
- hsl.s -= amount / 100;
- hsl.s = clamp01(hsl.s);
- return tinycolor(hsl);
- }
- function saturate(color, amount) {
- amount = (amount === 0) ? 0 : (amount || 10);
- var hsl = tinycolor(color).toHsl();
- hsl.s += amount / 100;
- hsl.s = clamp01(hsl.s);
- return tinycolor(hsl);
- }
- function greyscale(color) {
- return tinycolor(color).desaturate(100);
- }
- function lighten (color, amount) {
- amount = (amount === 0) ? 0 : (amount || 10);
- var hsl = tinycolor(color).toHsl();
- hsl.l += amount / 100;
- hsl.l = clamp01(hsl.l);
- return tinycolor(hsl);
- }
- function brighten(color, amount) {
- amount = (amount === 0) ? 0 : (amount || 10);
- var rgb = tinycolor(color).toRgb();
- rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
- rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
- rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
- return tinycolor(rgb);
- }
- function darken (color, amount) {
- amount = (amount === 0) ? 0 : (amount || 10);
- var hsl = tinycolor(color).toHsl();
- hsl.l -= amount / 100;
- hsl.l = clamp01(hsl.l);
- return tinycolor(hsl);
- }
- // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
- // Values outside of this range will be wrapped into this range.
- function spin(color, amount) {
- var hsl = tinycolor(color).toHsl();
- var hue = (hsl.h + amount) % 360;
- hsl.h = hue < 0 ? 360 + hue : hue;
- return tinycolor(hsl);
- }
- // Combination Functions
- // ---------------------
- // Thanks to jQuery xColor for some of the ideas behind these
- // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
- function complement(color) {
- var hsl = tinycolor(color).toHsl();
- hsl.h = (hsl.h + 180) % 360;
- return tinycolor(hsl);
- }
- function triad(color) {
- var hsl = tinycolor(color).toHsl();
- var h = hsl.h;
- return [
- tinycolor(color),
- tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
- tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
- ];
- }
- function tetrad(color) {
- var hsl = tinycolor(color).toHsl();
- var h = hsl.h;
- return [
- tinycolor(color),
- tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
- tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
- tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
- ];
- }
- function splitcomplement(color) {
- var hsl = tinycolor(color).toHsl();
- var h = hsl.h;
- return [
- tinycolor(color),
- tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
- tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
- ];
- }
- function analogous(color, results, slices) {
- results = results || 6;
- slices = slices || 30;
- var hsl = tinycolor(color).toHsl();
- var part = 360 / slices;
- var ret = [tinycolor(color)];
- for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
- hsl.h = (hsl.h + part) % 360;
- ret.push(tinycolor(hsl));
- }
- return ret;
- }
- function monochromatic(color, results) {
- results = results || 6;
- var hsv = tinycolor(color).toHsv();
- var h = hsv.h, s = hsv.s, v = hsv.v;
- var ret = [];
- var modification = 1 / results;
- while (results--) {
- ret.push(tinycolor({ h: h, s: s, v: v}));
- v = (v + modification) % 1;
- }
- return ret;
- }
- // Utility Functions
- // ---------------------
- tinycolor.mix = function(color1, color2, amount) {
- amount = (amount === 0) ? 0 : (amount || 50);
- var rgb1 = tinycolor(color1).toRgb();
- var rgb2 = tinycolor(color2).toRgb();
- var p = amount / 100;
- var rgba = {
- r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
- g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
- b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
- a: ((rgb2.a - rgb1.a) * p) + rgb1.a
- };
- return tinycolor(rgba);
- };
- // Readability Functions
- // ---------------------
- // <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)
- // `contrast`
- // Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
- tinycolor.readability = function(color1, color2) {
- var c1 = tinycolor(color1);
- var c2 = tinycolor(color2);
- return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
- };
- // `isReadable`
- // Ensure that foreground and background color combinations meet WCAG2 guidelines.
- // The third argument is an optional Object.
- // the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
- // the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
- // If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.
- // *Example*
- // tinycolor.isReadable("#000", "#111") => false
- // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
- tinycolor.isReadable = function(color1, color2, wcag2) {
- var readability = tinycolor.readability(color1, color2);
- var wcag2Parms, out;
- out = false;
- wcag2Parms = validateWCAG2Parms(wcag2);
- switch (wcag2Parms.level + wcag2Parms.size) {
- case "AAsmall":
- case "AAAlarge":
- out = readability >= 4.5;
- break;
- case "AAlarge":
- out = readability >= 3;
- break;
- case "AAAsmall":
- out = readability >= 7;
- break;
- }
- return out;
- };
- // `mostReadable`
- // Given a base color and a list of possible foreground or background
- // colors for that base, returns the most readable color.
- // Optionally returns Black or White if the most readable color is unreadable.
- // *Example*
- // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
- // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff"
- // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
- // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
- tinycolor.mostReadable = function(baseColor, colorList, args) {
- var bestColor = null;
- var bestScore = 0;
- var readability;
- var includeFallbackColors, level, size ;
- args = args || {};
- includeFallbackColors = args.includeFallbackColors ;
- level = args.level;
- size = args.size;
- for (var i= 0; i < colorList.length ; i++) {
- readability = tinycolor.readability(baseColor, colorList[i]);
- if (readability > bestScore) {
- bestScore = readability;
- bestColor = tinycolor(colorList[i]);
- }
- }
- if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
- return bestColor;
- }
- else {
- args.includeFallbackColors=false;
- return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
- }
- };
- // Big List of Colors
- // ------------------
- // <http://www.w3.org/TR/css3-color/#svg-color>
- var names = tinycolor.names = {
- aliceblue: "f0f8ff",
- antiquewhite: "faebd7",
- aqua: "0ff",
- aquamarine: "7fffd4",
- azure: "f0ffff",
- beige: "f5f5dc",
- bisque: "ffe4c4",
- black: "000",
- blanchedalmond: "ffebcd",
- blue: "00f",
- blueviolet: "8a2be2",
- brown: "a52a2a",
- burlywood: "deb887",
- burntsienna: "ea7e5d",
- cadetblue: "5f9ea0",
- chartreuse: "7fff00",
- chocolate: "d2691e",
- coral: "ff7f50",
- cornflowerblue: "6495ed",
- cornsilk: "fff8dc",
- crimson: "dc143c",
- cyan: "0ff",
- darkblue: "00008b",
- darkcyan: "008b8b",
- darkgoldenrod: "b8860b",
- darkgray: "a9a9a9",
- darkgreen: "006400",
- darkgrey: "a9a9a9",
- darkkhaki: "bdb76b",
- darkmagenta: "8b008b",
- darkolivegreen: "556b2f",
- darkorange: "ff8c00",
- darkorchid: "9932cc",
- darkred: "8b0000",
- darksalmon: "e9967a",
- darkseagreen: "8fbc8f",
- darkslateblue: "483d8b",
- darkslategray: "2f4f4f",
- darkslategrey: "2f4f4f",
- darkturquoise: "00ced1",
- darkviolet: "9400d3",
- deeppink: "ff1493",
- deepskyblue: "00bfff",
- dimgray: "696969",
- dimgrey: "696969",
- dodgerblue: "1e90ff",
- firebrick: "b22222",
- floralwhite: "fffaf0",
- forestgreen: "228b22",
- fuchsia: "f0f",
- gainsboro: "dcdcdc",
- ghostwhite: "f8f8ff",
- gold: "ffd700",
- goldenrod: "daa520",
- gray: "808080",
- green: "008000",
- greenyellow: "adff2f",
- grey: "808080",
- honeydew: "f0fff0",
- hotpink: "ff69b4",
- indianred: "cd5c5c",
- indigo: "4b0082",
- ivory: "fffff0",
- khaki: "f0e68c",
- lavender: "e6e6fa",
- lavenderblush: "fff0f5",
- lawngreen: "7cfc00",
- lemonchiffon: "fffacd",
- lightblue: "add8e6",
- lightcoral: "f08080",
- lightcyan: "e0ffff",
- lightgoldenrodyellow: "fafad2",
- lightgray: "d3d3d3",
- lightgreen: "90ee90",
- lightgrey: "d3d3d3",
- lightpink: "ffb6c1",
- lightsalmon: "ffa07a",
- lightseagreen: "20b2aa",
- lightskyblue: "87cefa",
- lightslategray: "789",
- lightslategrey: "789",
- lightsteelblue: "b0c4de",
- lightyellow: "ffffe0",
- lime: "0f0",
- limegreen: "32cd32",
- linen: "faf0e6",
- magenta: "f0f",
- maroon: "800000",
- mediumaquamarine: "66cdaa",
- mediumblue: "0000cd",
- mediumorchid: "ba55d3",
- mediumpurple: "9370db",
- mediumseagreen: "3cb371",
- mediumslateblue: "7b68ee",
- mediumspringgreen: "00fa9a",
- mediumturquoise: "48d1cc",
- mediumvioletred: "c71585",
- midnightblue: "191970",
- mintcream: "f5fffa",
- mistyrose: "ffe4e1",
- moccasin: "ffe4b5",
- navajowhite: "ffdead",
- navy: "000080",
- oldlace: "fdf5e6",
- olive: "808000",
- olivedrab: "6b8e23",
- orange: "ffa500",
- orangered: "ff4500",
- orchid: "da70d6",
- palegoldenrod: "eee8aa",
- palegreen: "98fb98",
- paleturquoise: "afeeee",
- palevioletred: "db7093",
- papayawhip: "ffefd5",
- peachpuff: "ffdab9",
- peru: "cd853f",
- pink: "ffc0cb",
- plum: "dda0dd",
- powderblue: "b0e0e6",
- purple: "800080",
- rebeccapurple: "663399",
- red: "f00",
- rosybrown: "bc8f8f",
- royalblue: "4169e1",
- saddlebrown: "8b4513",
- salmon: "fa8072",
- sandybrown: "f4a460",
- seagreen: "2e8b57",
- seashell: "fff5ee",
- sienna: "a0522d",
- silver: "c0c0c0",
- skyblue: "87ceeb",
- slateblue: "6a5acd",
- slategray: "708090",
- slategrey: "708090",
- snow: "fffafa",
- springgreen: "00ff7f",
- steelblue: "4682b4",
- tan: "d2b48c",
- teal: "008080",
- thistle: "d8bfd8",
- tomato: "ff6347",
- turquoise: "40e0d0",
- violet: "ee82ee",
- wheat: "f5deb3",
- white: "fff",
- whitesmoke: "f5f5f5",
- yellow: "ff0",
- yellowgreen: "9acd32"
- };
- // Make it easy to access colors via `hexNames[hex]`
- var hexNames = tinycolor.hexNames = flip(names);
- // Utilities
- // ---------
- // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
- function flip(o) {
- var flipped = { };
- for (var i in o) {
- if (o.hasOwnProperty(i)) {
- flipped[o[i]] = i;
- }
- }
- return flipped;
- }
- // Return a valid alpha value [0,1] with all invalid values being set to 1
- function boundAlpha(a) {
- a = parseFloat(a);
- if (isNaN(a) || a < 0 || a > 1) {
- a = 1;
- }
- return a;
- }
- // Take input from [0, n] and return it as [0, 1]
- function bound01(n, max) {
- if (isOnePointZero(n)) { n = "100%"; }
- var processPercent = isPercentage(n);
- n = mathMin(max, mathMax(0, parseFloat(n)));
- // Automatically convert percentage into number
- if (processPercent) {
- n = parseInt(n * max, 10) / 100;
- }
- // Handle floating point rounding errors
- if ((Math.abs(n - max) < 0.000001)) {
- return 1;
- }
- // Convert into [0, 1] range if it isn't already
- return (n % max) / parseFloat(max);
- }
- // Force a number between 0 and 1
- function clamp01(val) {
- return mathMin(1, mathMax(0, val));
- }
- // Parse a base-16 hex value into a base-10 integer
- function parseIntFromHex(val) {
- return parseInt(val, 16);
- }
- // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
- // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
- function isOnePointZero(n) {
- return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
- }
- // Check to see if string passed in is a percentage
- function isPercentage(n) {
- return typeof n === "string" && n.indexOf('%') != -1;
- }
- // Force a hex value to have 2 characters
- function pad2(c) {
- return c.length == 1 ? '0' + c : '' + c;
- }
- // Replace a decimal with it's percentage value
- function convertToPercentage(n) {
- if (n <= 1) {
- n = (n * 100) + "%";
- }
- return n;
- }
- // Converts a decimal to a hex value
- function convertDecimalToHex(d) {
- return Math.round(parseFloat(d) * 255).toString(16);
- }
- // Converts a hex value to a decimal
- function convertHexToDecimal(h) {
- return (parseIntFromHex(h) / 255);
- }
- var matchers = (function() {
- // <http://www.w3.org/TR/css3-values/#integers>
- var CSS_INTEGER = "[-\\+]?\\d+%?";
- // <http://www.w3.org/TR/css3-values/#number-value>
- var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
- // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
- var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
- // Actual matching.
- // Parentheses and commas are optional, but not required.
- // Whitespace can take the place of commas or opening paren
- var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
- var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
- return {
- CSS_UNIT: new RegExp(CSS_UNIT),
- rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
- rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
- hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
- hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
- hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
- hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
- hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
- hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
- hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
- hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
- };
- })();
- // `isValidCSSUnit`
- // Take in a single string / number and check to see if it looks like a CSS unit
- // (see `matchers` above for definition).
- function isValidCSSUnit(color) {
- return !!matchers.CSS_UNIT.exec(color);
- }
- // `stringInputToObject`
- // Permissive string parsing. Take in a number of formats, and output an object
- // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
- function stringInputToObject(color) {
- color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
- var named = false;
- if (names[color]) {
- color = names[color];
- named = true;
- }
- else if (color == 'transparent') {
- return { r: 0, g: 0, b: 0, a: 0, format: "name" };
- }
- // Try to match string input using regular expressions.
- // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
- // Just return an object and let the conversion functions handle that.
- // This way the result will be the same whether the tinycolor is initialized with string or object.
- var match;
- if ((match = matchers.rgb.exec(color))) {
- return { r: match[1], g: match[2], b: match[3] };
- }
- if ((match = matchers.rgba.exec(color))) {
- return { r: match[1], g: match[2], b: match[3], a: match[4] };
- }
- if ((match = matchers.hsl.exec(color))) {
- return { h: match[1], s: match[2], l: match[3] };
- }
- if ((match = matchers.hsla.exec(color))) {
- return { h: match[1], s: match[2], l: match[3], a: match[4] };
- }
- if ((match = matchers.hsv.exec(color))) {
- return { h: match[1], s: match[2], v: match[3] };
- }
- if ((match = matchers.hsva.exec(color))) {
- return { h: match[1], s: match[2], v: match[3], a: match[4] };
- }
- if ((match = matchers.hex8.exec(color))) {
- return {
- r: parseIntFromHex(match[1]),
- g: parseIntFromHex(match[2]),
- b: parseIntFromHex(match[3]),
- a: convertHexToDecimal(match[4]),
- format: named ? "name" : "hex8"
- };
- }
- if ((match = matchers.hex6.exec(color))) {
- return {
- r: parseIntFromHex(match[1]),
- g: parseIntFromHex(match[2]),
- b: parseIntFromHex(match[3]),
- format: named ? "name" : "hex"
- };
- }
- if ((match = matchers.hex4.exec(color))) {
- return {
- r: parseIntFromHex(match[1] + '' + match[1]),
- g: parseIntFromHex(match[2] + '' + match[2]),
- b: parseIntFromHex(match[3] + '' + match[3]),
- a: convertHexToDecimal(match[4] + '' + match[4]),
- format: named ? "name" : "hex8"
- };
- }
- if ((match = matchers.hex3.exec(color))) {
- return {
- r: parseIntFromHex(match[1] + '' + match[1]),
- g: parseIntFromHex(match[2] + '' + match[2]),
- b: parseIntFromHex(match[3] + '' + match[3]),
- format: named ? "name" : "hex"
- };
- }
- return false;
- }
- function validateWCAG2Parms(parms) {
- // return valid WCAG2 parms for isReadable.
- // If input parms are invalid, return {"level":"AA", "size":"small"}
- var level, size;
- parms = parms || {"level":"AA", "size":"small"};
- level = (parms.level || "AA").toUpperCase();
- size = (parms.size || "small").toLowerCase();
- if (level !== "AA" && level !== "AAA") {
- level = "AA";
- }
- if (size !== "small" && size !== "large") {
- size = "small";
- }
- return {"level":level, "size":size};
- }
- // Node: Export function
- if (typeof module !== "undefined" && module.exports) {
- module.exports = tinycolor;
- }
- // AMD/requirejs: Define the module
- else if (typeof define === 'function' && define.amd) {
- define(function () {return tinycolor;});
- }
- // Browser: Expose to window
- else {
- window.tinycolor = tinycolor;
- }
- })(Math);
- },{}],358:[function(require,module,exports){
- exports = module.exports = trim;
- function trim(str){
- return str.replace(/^\s*|\s*$/g, '');
- }
- exports.left = function(str){
- return str.replace(/^\s*/, '');
- };
- exports.right = function(str){
- return str.replace(/\s*$/, '');
- };
- },{}],359:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- 'use strict';
- var punycode = require('punycode');
- var util = require('./util');
- exports.parse = urlParse;
- exports.resolve = urlResolve;
- exports.resolveObject = urlResolveObject;
- exports.format = urlFormat;
- exports.Url = Url;
- function Url() {
- this.protocol = null;
- this.slashes = null;
- this.auth = null;
- this.host = null;
- this.port = null;
- this.hostname = null;
- this.hash = null;
- this.search = null;
- this.query = null;
- this.pathname = null;
- this.path = null;
- this.href = null;
- }
- // Reference: RFC 3986, RFC 1808, RFC 2396
- // define these here so at least they only have to be
- // compiled once on the first module load.
- var protocolPattern = /^([a-z0-9.+-]+:)/i,
- portPattern = /:[0-9]*$/,
- // Special case for a simple path URL
- simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
- // RFC 2396: characters reserved for delimiting URLs.
- // We actually just auto-escape these.
- delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
- // RFC 2396: characters not allowed for various reasons.
- unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
- // Allowed by RFCs, but cause of XSS attacks. Always escape these.
- autoEscape = ['\''].concat(unwise),
- // Characters that are never ever allowed in a hostname.
- // Note that any invalid chars are also handled, but these
- // are the ones that are *expected* to be seen, so we fast-path
- // them.
- nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
- hostEndingChars = ['/', '?', '#'],
- hostnameMaxLen = 255,
- hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
- hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
- // protocols that can allow "unsafe" and "unwise" chars.
- unsafeProtocol = {
- 'javascript': true,
- 'javascript:': true
- },
- // protocols that never have a hostname.
- hostlessProtocol = {
- 'javascript': true,
- 'javascript:': true
- },
- // protocols that always contain a // bit.
- slashedProtocol = {
- 'http': true,
- 'https': true,
- 'ftp': true,
- 'gopher': true,
- 'file': true,
- 'http:': true,
- 'https:': true,
- 'ftp:': true,
- 'gopher:': true,
- 'file:': true
- },
- querystring = require('querystring');
- function urlParse(url, parseQueryString, slashesDenoteHost) {
- if (url && util.isObject(url) && url instanceof Url) return url;
- var u = new Url;
- u.parse(url, parseQueryString, slashesDenoteHost);
- return u;
- }
- Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
- if (!util.isString(url)) {
- throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
- }
- // Copy chrome, IE, opera backslash-handling behavior.
- // Back slashes before the query string get converted to forward slashes
- // See: https://code.google.com/p/chromium/issues/detail?id=25916
- var queryIndex = url.indexOf('?'),
- splitter =
- (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
- uSplit = url.split(splitter),
- slashRegex = /\\/g;
- uSplit[0] = uSplit[0].replace(slashRegex, '/');
- url = uSplit.join(splitter);
- var rest = url;
- // trim before proceeding.
- // This is to support parse stuff like " http://foo.com \n"
- rest = rest.trim();
- if (!slashesDenoteHost && url.split('#').length === 1) {
- // Try fast path regexp
- var simplePath = simplePathPattern.exec(rest);
- if (simplePath) {
- this.path = rest;
- this.href = rest;
- this.pathname = simplePath[1];
- if (simplePath[2]) {
- this.search = simplePath[2];
- if (parseQueryString) {
- this.query = querystring.parse(this.search.substr(1));
- } else {
- this.query = this.search.substr(1);
- }
- } else if (parseQueryString) {
- this.search = '';
- this.query = {};
- }
- return this;
- }
- }
- var proto = protocolPattern.exec(rest);
- if (proto) {
- proto = proto[0];
- var lowerProto = proto.toLowerCase();
- this.protocol = lowerProto;
- rest = rest.substr(proto.length);
- }
- // figure out if it's got a host
- // user@server is *always* interpreted as a hostname, and url
- // resolution will treat //foo/bar as host=foo,path=bar because that's
- // how the browser resolves relative URLs.
- if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
- var slashes = rest.substr(0, 2) === '//';
- if (slashes && !(proto && hostlessProtocol[proto])) {
- rest = rest.substr(2);
- this.slashes = true;
- }
- }
- if (!hostlessProtocol[proto] &&
- (slashes || (proto && !slashedProtocol[proto]))) {
- // there's a hostname.
- // the first instance of /, ?, ;, or # ends the host.
- //
- // If there is an @ in the hostname, then non-host chars *are* allowed
- // to the left of the last @ sign, unless some host-ending character
- // comes *before* the @-sign.
- // URLs are obnoxious.
- //
- // ex:
- // http://a@b@c/ => user:a@b host:c
- // http://a@b?@c => user:a host:c path:/?@c
- // v0.12 TODO(isaacs): This is not quite how Chrome does things.
- // Review our test case against browsers more comprehensively.
- // find the first instance of any hostEndingChars
- var hostEnd = -1;
- for (var i = 0; i < hostEndingChars.length; i++) {
- var hec = rest.indexOf(hostEndingChars[i]);
- if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
- hostEnd = hec;
- }
- // at this point, either we have an explicit point where the
- // auth portion cannot go past, or the last @ char is the decider.
- var auth, atSign;
- if (hostEnd === -1) {
- // atSign can be anywhere.
- atSign = rest.lastIndexOf('@');
- } else {
- // atSign must be in auth portion.
- // http://a@b/c@d => host:b auth:a path:/c@d
- atSign = rest.lastIndexOf('@', hostEnd);
- }
- // Now we have a portion which is definitely the auth.
- // Pull that off.
- if (atSign !== -1) {
- auth = rest.slice(0, atSign);
- rest = rest.slice(atSign + 1);
- this.auth = decodeURIComponent(auth);
- }
- // the host is the remaining to the left of the first non-host char
- hostEnd = -1;
- for (var i = 0; i < nonHostChars.length; i++) {
- var hec = rest.indexOf(nonHostChars[i]);
- if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
- hostEnd = hec;
- }
- // if we still have not hit it, then the entire thing is a host.
- if (hostEnd === -1)
- hostEnd = rest.length;
- this.host = rest.slice(0, hostEnd);
- rest = rest.slice(hostEnd);
- // pull out port.
- this.parseHost();
- // we've indicated that there is a hostname,
- // so even if it's empty, it has to be present.
- this.hostname = this.hostname || '';
- // if hostname begins with [ and ends with ]
- // assume that it's an IPv6 address.
- var ipv6Hostname = this.hostname[0] === '[' &&
- this.hostname[this.hostname.length - 1] === ']';
- // validate a little.
- if (!ipv6Hostname) {
- var hostparts = this.hostname.split(/\./);
- for (var i = 0, l = hostparts.length; i < l; i++) {
- var part = hostparts[i];
- if (!part) continue;
- if (!part.match(hostnamePartPattern)) {
- var newpart = '';
- for (var j = 0, k = part.length; j < k; j++) {
- if (part.charCodeAt(j) > 127) {
- // we replace non-ASCII char with a temporary placeholder
- // we need this to make sure size of hostname is not
- // broken by replacing non-ASCII by nothing
- newpart += 'x';
- } else {
- newpart += part[j];
- }
- }
- // we test again with ASCII char only
- if (!newpart.match(hostnamePartPattern)) {
- var validParts = hostparts.slice(0, i);
- var notHost = hostparts.slice(i + 1);
- var bit = part.match(hostnamePartStart);
- if (bit) {
- validParts.push(bit[1]);
- notHost.unshift(bit[2]);
- }
- if (notHost.length) {
- rest = '/' + notHost.join('.') + rest;
- }
- this.hostname = validParts.join('.');
- break;
- }
- }
- }
- }
- if (this.hostname.length > hostnameMaxLen) {
- this.hostname = '';
- } else {
- // hostnames are always lower case.
- this.hostname = this.hostname.toLowerCase();
- }
- if (!ipv6Hostname) {
- // IDNA Support: Returns a punycoded representation of "domain".
- // It only converts parts of the domain name that
- // have non-ASCII characters, i.e. it doesn't matter if
- // you call it with a domain that already is ASCII-only.
- this.hostname = punycode.toASCII(this.hostname);
- }
- var p = this.port ? ':' + this.port : '';
- var h = this.hostname || '';
- this.host = h + p;
- this.href += this.host;
- // strip [ and ] from the hostname
- // the host field still retains them, though
- if (ipv6Hostname) {
- this.hostname = this.hostname.substr(1, this.hostname.length - 2);
- if (rest[0] !== '/') {
- rest = '/' + rest;
- }
- }
- }
- // now rest is set to the post-host stuff.
- // chop off any delim chars.
- if (!unsafeProtocol[lowerProto]) {
- // First, make 100% sure that any "autoEscape" chars get
- // escaped, even if encodeURIComponent doesn't think they
- // need to be.
- for (var i = 0, l = autoEscape.length; i < l; i++) {
- var ae = autoEscape[i];
- if (rest.indexOf(ae) === -1)
- continue;
- var esc = encodeURIComponent(ae);
- if (esc === ae) {
- esc = escape(ae);
- }
- rest = rest.split(ae).join(esc);
- }
- }
- // chop off from the tail first.
- var hash = rest.indexOf('#');
- if (hash !== -1) {
- // got a fragment string.
- this.hash = rest.substr(hash);
- rest = rest.slice(0, hash);
- }
- var qm = rest.indexOf('?');
- if (qm !== -1) {
- this.search = rest.substr(qm);
- this.query = rest.substr(qm + 1);
- if (parseQueryString) {
- this.query = querystring.parse(this.query);
- }
- rest = rest.slice(0, qm);
- } else if (parseQueryString) {
- // no query string, but parseQueryString still requested
- this.search = '';
- this.query = {};
- }
- if (rest) this.pathname = rest;
- if (slashedProtocol[lowerProto] &&
- this.hostname && !this.pathname) {
- this.pathname = '/';
- }
- //to support http.request
- if (this.pathname || this.search) {
- var p = this.pathname || '';
- var s = this.search || '';
- this.path = p + s;
- }
- // finally, reconstruct the href based on what has been validated.
- this.href = this.format();
- return this;
- };
- // format a parsed object into a url string
- function urlFormat(obj) {
- // ensure it's an object, and not a string url.
- // If it's an obj, this is a no-op.
- // this way, you can call url_format() on strings
- // to clean up potentially wonky urls.
- if (util.isString(obj)) obj = urlParse(obj);
- if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
- return obj.format();
- }
- Url.prototype.format = function() {
- var auth = this.auth || '';
- if (auth) {
- auth = encodeURIComponent(auth);
- auth = auth.replace(/%3A/i, ':');
- auth += '@';
- }
- var protocol = this.protocol || '',
- pathname = this.pathname || '',
- hash = this.hash || '',
- host = false,
- query = '';
- if (this.host) {
- host = auth + this.host;
- } else if (this.hostname) {
- host = auth + (this.hostname.indexOf(':') === -1 ?
- this.hostname :
- '[' + this.hostname + ']');
- if (this.port) {
- host += ':' + this.port;
- }
- }
- if (this.query &&
- util.isObject(this.query) &&
- Object.keys(this.query).length) {
- query = querystring.stringify(this.query);
- }
- var search = this.search || (query && ('?' + query)) || '';
- if (protocol && protocol.substr(-1) !== ':') protocol += ':';
- // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
- // unless they had them to begin with.
- if (this.slashes ||
- (!protocol || slashedProtocol[protocol]) && host !== false) {
- host = '//' + (host || '');
- if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
- } else if (!host) {
- host = '';
- }
- if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
- if (search && search.charAt(0) !== '?') search = '?' + search;
- pathname = pathname.replace(/[?#]/g, function(match) {
- return encodeURIComponent(match);
- });
- search = search.replace('#', '%23');
- return protocol + host + pathname + search + hash;
- };
- function urlResolve(source, relative) {
- return urlParse(source, false, true).resolve(relative);
- }
- Url.prototype.resolve = function(relative) {
- return this.resolveObject(urlParse(relative, false, true)).format();
- };
- function urlResolveObject(source, relative) {
- if (!source) return relative;
- return urlParse(source, false, true).resolveObject(relative);
- }
- Url.prototype.resolveObject = function(relative) {
- if (util.isString(relative)) {
- var rel = new Url();
- rel.parse(relative, false, true);
- relative = rel;
- }
- var result = new Url();
- var tkeys = Object.keys(this);
- for (var tk = 0; tk < tkeys.length; tk++) {
- var tkey = tkeys[tk];
- result[tkey] = this[tkey];
- }
- // hash is always overridden, no matter what.
- // even href="" will remove it.
- result.hash = relative.hash;
- // if the relative url is empty, then there's nothing left to do here.
- if (relative.href === '') {
- result.href = result.format();
- return result;
- }
- // hrefs like //foo/bar always cut to the protocol.
- if (relative.slashes && !relative.protocol) {
- // take everything except the protocol from relative
- var rkeys = Object.keys(relative);
- for (var rk = 0; rk < rkeys.length; rk++) {
- var rkey = rkeys[rk];
- if (rkey !== 'protocol')
- result[rkey] = relative[rkey];
- }
- //urlParse appends trailing / to urls like http://www.example.com
- if (slashedProtocol[result.protocol] &&
- result.hostname && !result.pathname) {
- result.path = result.pathname = '/';
- }
- result.href = result.format();
- return result;
- }
- if (relative.protocol && relative.protocol !== result.protocol) {
- // if it's a known url protocol, then changing
- // the protocol does weird things
- // first, if it's not file:, then we MUST have a host,
- // and if there was a path
- // to begin with, then we MUST have a path.
- // if it is file:, then the host is dropped,
- // because that's known to be hostless.
- // anything else is assumed to be absolute.
- if (!slashedProtocol[relative.protocol]) {
- var keys = Object.keys(relative);
- for (var v = 0; v < keys.length; v++) {
- var k = keys[v];
- result[k] = relative[k];
- }
- result.href = result.format();
- return result;
- }
- result.protocol = relative.protocol;
- if (!relative.host && !hostlessProtocol[relative.protocol]) {
- var relPath = (relative.pathname || '').split('/');
- while (relPath.length && !(relative.host = relPath.shift()));
- if (!relative.host) relative.host = '';
- if (!relative.hostname) relative.hostname = '';
- if (relPath[0] !== '') relPath.unshift('');
- if (relPath.length < 2) relPath.unshift('');
- result.pathname = relPath.join('/');
- } else {
- result.pathname = relative.pathname;
- }
- result.search = relative.search;
- result.query = relative.query;
- result.host = relative.host || '';
- result.auth = relative.auth;
- result.hostname = relative.hostname || relative.host;
- result.port = relative.port;
- // to support http.request
- if (result.pathname || result.search) {
- var p = result.pathname || '';
- var s = result.search || '';
- result.path = p + s;
- }
- result.slashes = result.slashes || relative.slashes;
- result.href = result.format();
- return result;
- }
- var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
- isRelAbs = (
- relative.host ||
- relative.pathname && relative.pathname.charAt(0) === '/'
- ),
- mustEndAbs = (isRelAbs || isSourceAbs ||
- (result.host && relative.pathname)),
- removeAllDots = mustEndAbs,
- srcPath = result.pathname && result.pathname.split('/') || [],
- relPath = relative.pathname && relative.pathname.split('/') || [],
- psychotic = result.protocol && !slashedProtocol[result.protocol];
- // if the url is a non-slashed url, then relative
- // links like ../.. should be able
- // to crawl up to the hostname, as well. This is strange.
- // result.protocol has already been set by now.
- // Later on, put the first path part into the host field.
- if (psychotic) {
- result.hostname = '';
- result.port = null;
- if (result.host) {
- if (srcPath[0] === '') srcPath[0] = result.host;
- else srcPath.unshift(result.host);
- }
- result.host = '';
- if (relative.protocol) {
- relative.hostname = null;
- relative.port = null;
- if (relative.host) {
- if (relPath[0] === '') relPath[0] = relative.host;
- else relPath.unshift(relative.host);
- }
- relative.host = null;
- }
- mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
- }
- if (isRelAbs) {
- // it's absolute.
- result.host = (relative.host || relative.host === '') ?
- relative.host : result.host;
- result.hostname = (relative.hostname || relative.hostname === '') ?
- relative.hostname : result.hostname;
- result.search = relative.search;
- result.query = relative.query;
- srcPath = relPath;
- // fall through to the dot-handling below.
- } else if (relPath.length) {
- // it's relative
- // throw away the existing file, and take the new path instead.
- if (!srcPath) srcPath = [];
- srcPath.pop();
- srcPath = srcPath.concat(relPath);
- result.search = relative.search;
- result.query = relative.query;
- } else if (!util.isNullOrUndefined(relative.search)) {
- // just pull out the search.
- // like href='?foo'.
- // Put this after the other two cases because it simplifies the booleans
- if (psychotic) {
- result.hostname = result.host = srcPath.shift();
- //occationaly the auth can get stuck only in host
- //this especially happens in cases like
- //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
- var authInHost = result.host && result.host.indexOf('@') > 0 ?
- result.host.split('@') : false;
- if (authInHost) {
- result.auth = authInHost.shift();
- result.host = result.hostname = authInHost.shift();
- }
- }
- result.search = relative.search;
- result.query = relative.query;
- //to support http.request
- if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
- result.path = (result.pathname ? result.pathname : '') +
- (result.search ? result.search : '');
- }
- result.href = result.format();
- return result;
- }
- if (!srcPath.length) {
- // no path at all. easy.
- // we've already handled the other stuff above.
- result.pathname = null;
- //to support http.request
- if (result.search) {
- result.path = '/' + result.search;
- } else {
- result.path = null;
- }
- result.href = result.format();
- return result;
- }
- // if a url ENDs in . or .., then it must get a trailing slash.
- // however, if it ends in anything else non-slashy,
- // then it must NOT get a trailing slash.
- var last = srcPath.slice(-1)[0];
- var hasTrailingSlash = (
- (result.host || relative.host || srcPath.length > 1) &&
- (last === '.' || last === '..') || last === '');
- // strip single dots, resolve double dots to parent dir
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = srcPath.length; i >= 0; i--) {
- last = srcPath[i];
- if (last === '.') {
- srcPath.splice(i, 1);
- } else if (last === '..') {
- srcPath.splice(i, 1);
- up++;
- } else if (up) {
- srcPath.splice(i, 1);
- up--;
- }
- }
- // if the path is allowed to go above the root, restore leading ..s
- if (!mustEndAbs && !removeAllDots) {
- for (; up--; up) {
- srcPath.unshift('..');
- }
- }
- if (mustEndAbs && srcPath[0] !== '' &&
- (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
- srcPath.unshift('');
- }
- if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
- srcPath.push('');
- }
- var isAbsolute = srcPath[0] === '' ||
- (srcPath[0] && srcPath[0].charAt(0) === '/');
- // put the host back
- if (psychotic) {
- result.hostname = result.host = isAbsolute ? '' :
- srcPath.length ? srcPath.shift() : '';
- //occationaly the auth can get stuck only in host
- //this especially happens in cases like
- //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
- var authInHost = result.host && result.host.indexOf('@') > 0 ?
- result.host.split('@') : false;
- if (authInHost) {
- result.auth = authInHost.shift();
- result.host = result.hostname = authInHost.shift();
- }
- }
- mustEndAbs = mustEndAbs || (result.host && srcPath.length);
- if (mustEndAbs && !isAbsolute) {
- srcPath.unshift('');
- }
- if (!srcPath.length) {
- result.pathname = null;
- result.path = null;
- } else {
- result.pathname = srcPath.join('/');
- }
- //to support request.http
- if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
- result.path = (result.pathname ? result.pathname : '') +
- (result.search ? result.search : '');
- }
- result.auth = relative.auth || result.auth;
- result.slashes = result.slashes || relative.slashes;
- result.href = result.format();
- return result;
- };
- Url.prototype.parseHost = function() {
- var host = this.host;
- var port = portPattern.exec(host);
- if (port) {
- port = port[0];
- if (port !== ':') {
- this.port = port.substr(1);
- }
- host = host.substr(0, host.length - port.length);
- }
- if (host) this.hostname = host;
- };
- },{"./util":360,"punycode":313,"querystring":316}],360:[function(require,module,exports){
- 'use strict';
- module.exports = {
- isString: function(arg) {
- return typeof(arg) === 'string';
- },
- isObject: function(arg) {
- return typeof(arg) === 'object' && arg !== null;
- },
- isNull: function(arg) {
- return arg === null;
- },
- isNullOrUndefined: function(arg) {
- return arg == null;
- }
- };
- },{}],361:[function(require,module,exports){
- (function (process){
- ;(function(){
- var UTIF = {};
- // Make available for import by `require()`
- if (typeof module == "object") {module.exports = UTIF;}
- else {self.UTIF = UTIF;}
- var pako;
- if (typeof require == "function") {pako = require("pako");}
- else {pako = self.pako;}
- function log() { if (typeof process=="undefined" || process.env.NODE_ENV=="development") console.log.apply(console, arguments); }
- (function(UTIF, pako){
-
- // Following lines add a JPEG decoder to UTIF.JpegDecoder
- (function(){var V="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(g){return typeof g}:function(g){return g&&"function"===typeof Symbol&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g},D=function(){function g(g){this.message="JPEG error: "+g}g.prototype=Error();g.prototype.name="JpegError";return g.constructor=g}(),P=function(){function g(g,D){this.message=g;this.g=D}g.prototype=Error();g.prototype.name="DNLMarkerError";return g.constructor=g}();(function(){function g(){this.M=
- null;this.B=-1}function W(a,d){for(var f=0,e=[],b,B,k=16;0<k&&!a[k-1];)k--;e.push({children:[],index:0});var l=e[0],r;for(b=0;b<k;b++){for(B=0;B<a[b];B++){l=e.pop();for(l.children[l.index]=d[f];0<l.index;)l=e.pop();l.index++;for(e.push(l);e.length<=b;)e.push(r={children:[],index:0}),l.children[l.index]=r.children,l=r;f++}b+1<k&&(e.push(r={children:[],index:0}),l.children[l.index]=r.children,l=r)}return e[0].children}function X(a,d,f,e,b,B,k,l,r){function n(){if(0<x)return x--,z>>x&1;z=a[d++];if(255===
- z){var c=a[d++];if(c){if(220===c&&g){d+=2;var b=a[d++]<<8|a[d++];if(0<b&&b!==f.g)throw new P("Found DNL marker (0xFFDC) while parsing scan data",b);}throw new D("unexpected marker "+(z<<8|c).toString(16));}}x=7;return z>>>7}function q(a){for(;;){a=a[n()];if("number"===typeof a)return a;if("object"!==("undefined"===typeof a?"undefined":V(a)))throw new D("invalid huffman sequence");}}function h(a){for(var c=0;0<a;)c=c<<1|n(),a--;return c}function c(a){if(1===a)return 1===n()?1:-1;var c=h(a);return c>=
- 1<<a-1?c:c+(-1<<a)+1}function C(a,b){var d=q(a.D);d=0===d?0:c(d);a.a[b]=a.m+=d;for(d=1;64>d;){var h=q(a.o),k=h&15;h>>=4;if(0===k){if(15>h)break;d+=16}else d+=h,a.a[b+J[d]]=c(k),d++}}function w(a,d){var b=q(a.D);b=0===b?0:c(b)<<r;a.a[d]=a.m+=b}function p(a,c){a.a[c]|=n()<<r}function m(a,b){if(0<A)A--;else for(var d=B;d<=k;){var e=q(a.o),f=e&15;e>>=4;if(0===f){if(15>e){A=h(e)+(1<<e)-1;break}d+=16}else d+=e,a.a[b+J[d]]=c(f)*(1<<r),d++}}function t(a,d){for(var b=B,e=0,f;b<=k;){f=d+J[b];var l=0>a.a[f]?
- -1:1;switch(E){case 0:e=q(a.o);f=e&15;e>>=4;if(0===f)15>e?(A=h(e)+(1<<e),E=4):(e=16,E=1);else{if(1!==f)throw new D("invalid ACn encoding");Q=c(f);E=e?2:3}continue;case 1:case 2:a.a[f]?a.a[f]+=l*(n()<<r):(e--,0===e&&(E=2===E?3:0));break;case 3:a.a[f]?a.a[f]+=l*(n()<<r):(a.a[f]=Q<<r,E=0);break;case 4:a.a[f]&&(a.a[f]+=l*(n()<<r))}b++}4===E&&(A--,0===A&&(E=0))}var g=9<arguments.length&&void 0!==arguments[9]?arguments[9]:!1,u=f.P,v=d,z=0,x=0,A=0,E=0,Q,K=e.length,F,L,M,I;var R=f.S?0===B?0===l?w:p:0===l?
- m:t:C;var G=0;var O=1===K?e[0].c*e[0].l:u*f.O;for(var S,T;G<O;){var U=b?Math.min(O-G,b):O;for(F=0;F<K;F++)e[F].m=0;A=0;if(1===K){var y=e[0];for(I=0;I<U;I++)R(y,64*((y.c+1)*(G/y.c|0)+G%y.c)),G++}else for(I=0;I<U;I++){for(F=0;F<K;F++)for(y=e[F],S=y.h,T=y.j,L=0;L<T;L++)for(M=0;M<S;M++)R(y,64*((y.c+1)*((G/u|0)*y.j+L)+(G%u*y.h+M)));G++}x=0;(y=N(a,d))&&y.f&&((0,_util.warn)("decodeScan - unexpected MCU data, current marker is: "+y.f),d=y.offset);y=y&&y.F;if(!y||65280>=y)throw new D("marker was not found");
- if(65488<=y&&65495>=y)d+=2;else break}(y=N(a,d))&&y.f&&((0,_util.warn)("decodeScan - unexpected Scan data, current marker is: "+y.f),d=y.offset);return d-v}function Y(a,d){for(var f=d.c,e=d.l,b=new Int16Array(64),B=0;B<e;B++)for(var k=0;k<f;k++){var l=64*((d.c+1)*B+k),r=b,n=d.G,q=d.a;if(!n)throw new D("missing required Quantization Table.");for(var h=0;64>h;h+=8){var c=q[l+h];var C=q[l+h+1];var w=q[l+h+2];var p=q[l+h+3];var m=q[l+h+4];var t=q[l+h+5];var g=q[l+h+6];var u=q[l+h+7];c*=n[h];if(0===(C|
- w|p|m|t|g|u))c=5793*c+512>>10,r[h]=c,r[h+1]=c,r[h+2]=c,r[h+3]=c,r[h+4]=c,r[h+5]=c,r[h+6]=c,r[h+7]=c;else{C*=n[h+1];w*=n[h+2];p*=n[h+3];m*=n[h+4];t*=n[h+5];g*=n[h+6];u*=n[h+7];var v=5793*c+128>>8;var z=5793*m+128>>8;var x=w;var A=g;m=2896*(C-u)+128>>8;u=2896*(C+u)+128>>8;p<<=4;t<<=4;v=v+z+1>>1;z=v-z;c=3784*x+1567*A+128>>8;x=1567*x-3784*A+128>>8;A=c;m=m+t+1>>1;t=m-t;u=u+p+1>>1;p=u-p;v=v+A+1>>1;A=v-A;z=z+x+1>>1;x=z-x;c=2276*m+3406*u+2048>>12;m=3406*m-2276*u+2048>>12;u=c;c=799*p+4017*t+2048>>12;p=4017*
- p-799*t+2048>>12;t=c;r[h]=v+u;r[h+7]=v-u;r[h+1]=z+t;r[h+6]=z-t;r[h+2]=x+p;r[h+5]=x-p;r[h+3]=A+m;r[h+4]=A-m}}for(n=0;8>n;++n)c=r[n],C=r[n+8],w=r[n+16],p=r[n+24],m=r[n+32],t=r[n+40],g=r[n+48],u=r[n+56],0===(C|w|p|m|t|g|u)?(c=5793*c+8192>>14,c=-2040>c?0:2024<=c?255:c+2056>>4,q[l+n]=c,q[l+n+8]=c,q[l+n+16]=c,q[l+n+24]=c,q[l+n+32]=c,q[l+n+40]=c,q[l+n+48]=c,q[l+n+56]=c):(v=5793*c+2048>>12,z=5793*m+2048>>12,x=w,A=g,m=2896*(C-u)+2048>>12,u=2896*(C+u)+2048>>12,v=(v+z+1>>1)+4112,z=v-z,c=3784*x+1567*A+2048>>
- 12,x=1567*x-3784*A+2048>>12,A=c,m=m+t+1>>1,t=m-t,u=u+p+1>>1,p=u-p,v=v+A+1>>1,A=v-A,z=z+x+1>>1,x=z-x,c=2276*m+3406*u+2048>>12,m=3406*m-2276*u+2048>>12,u=c,c=799*p+4017*t+2048>>12,p=4017*p-799*t+2048>>12,t=c,c=v+u,u=v-u,C=z+t,g=z-t,w=x+p,t=x-p,p=A+m,m=A-m,c=16>c?0:4080<=c?255:c>>4,C=16>C?0:4080<=C?255:C>>4,w=16>w?0:4080<=w?255:w>>4,p=16>p?0:4080<=p?255:p>>4,m=16>m?0:4080<=m?255:m>>4,t=16>t?0:4080<=t?255:t>>4,g=16>g?0:4080<=g?255:g>>4,u=16>u?0:4080<=u?255:u>>4,q[l+n]=c,q[l+n+8]=C,q[l+n+16]=w,q[l+n+24]=
- p,q[l+n+32]=m,q[l+n+40]=t,q[l+n+48]=g,q[l+n+56]=u)}return d.a}function N(a,d){var f=2<arguments.length&&void 0!==arguments[2]?arguments[2]:d,e=a.length-1;f=f<d?f:d;if(d>=e)return null;var b=a[d]<<8|a[d+1];if(65472<=b&&65534>=b)return{f:null,F:b,offset:d};for(var B=a[f]<<8|a[f+1];!(65472<=B&&65534>=B);){if(++f>=e)return null;B=a[f]<<8|a[f+1]}return{f:b.toString(16),F:B,offset:f}}var J=new Uint8Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,
- 57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]);g.prototype={parse:function(a){function d(){var d=a[k]<<8|a[k+1];k+=2;return d}function f(){var b=d();b=k+b-2;var c=N(a,b,k);c&&c.f&&((0,_util.warn)("readDataBlock - incorrect length, current marker is: "+c.f),b=c.offset);b=a.subarray(k,b);k+=b.length;return b}function e(a){for(var b=Math.ceil(a.v/8/a.s),c=Math.ceil(a.g/8/a.u),d=0;d<a.b.length;d++){v=a.b[d];var e=Math.ceil(Math.ceil(a.v/8)*v.h/a.s),f=Math.ceil(Math.ceil(a.g/
- 8)*v.j/a.u);v.a=new Int16Array(64*c*v.j*(b*v.h+1));v.c=e;v.l=f}a.P=b;a.O=c}var b=(1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}).N,B=void 0===b?null:b,k=0,l=null,r=0;b=[];var n=[],q=[],h=d();if(65496!==h)throw new D("SOI not found");for(h=d();65497!==h;){switch(h){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var c=f();65518===h&&65===c[0]&&100===
- c[1]&&111===c[2]&&98===c[3]&&101===c[4]&&(l={version:c[5]<<8|c[6],Y:c[7]<<8|c[8],Z:c[9]<<8|c[10],W:c[11]});break;case 65499:h=d()+k-2;for(var g;k<h;){var w=a[k++],p=new Uint16Array(64);if(0===w>>4)for(c=0;64>c;c++)g=J[c],p[g]=a[k++];else if(1===w>>4)for(c=0;64>c;c++)g=J[c],p[g]=d();else throw new D("DQT - invalid table spec");b[w&15]=p}break;case 65472:case 65473:case 65474:if(m)throw new D("Only single frame JPEGs supported");d();var m={};m.X=65473===h;m.S=65474===h;m.precision=a[k++];h=d();m.g=
- B||h;m.v=d();m.b=[];m.C={};c=a[k++];for(h=p=w=0;h<c;h++){g=a[k];var t=a[k+1]>>4;var H=a[k+1]&15;w<t&&(w=t);p<H&&(p=H);t=m.b.push({h:t,j:H,T:a[k+2],G:null});m.C[g]=t-1;k+=3}m.s=w;m.u=p;e(m);break;case 65476:g=d();for(h=2;h<g;){w=a[k++];p=new Uint8Array(16);for(c=t=0;16>c;c++,k++)t+=p[c]=a[k];H=new Uint8Array(t);for(c=0;c<t;c++,k++)H[c]=a[k];h+=17+t;(0===w>>4?q:n)[w&15]=W(p,H)}break;case 65501:d();var u=d();break;case 65498:c=1===++r&&!B;d();w=a[k++];g=[];for(h=0;h<w;h++){p=m.C[a[k++]];var v=m.b[p];
- p=a[k++];v.D=q[p>>4];v.o=n[p&15];g.push(v)}h=a[k++];w=a[k++];p=a[k++];try{var z=X(a,k,m,g,u,h,w,p>>4,p&15,c);k+=z}catch(x){if(x instanceof P)return(0,_util.warn)('Attempting to re-parse JPEG image using "scanLines" parameter found in DNL marker (0xFFDC) segment.'),this.parse(a,{N:x.g});throw x;}break;case 65500:k+=4;break;case 65535:255!==a[k]&&k--;break;default:if(255===a[k-3]&&192<=a[k-2]&&254>=a[k-2])k-=3;else if((c=N(a,k-2))&&c.f)(0,_util.warn)("JpegImage.parse - unexpected data, current marker is: "+
- c.f),k=c.offset;else throw new D("unknown marker "+h.toString(16));}h=d()}this.width=m.v;this.height=m.g;this.A=l;this.b=[];for(h=0;h<m.b.length;h++){v=m.b[h];if(u=b[v.T])v.G=u;this.b.push({R:Y(m,v),U:v.h/m.s,V:v.j/m.u,c:v.c,l:v.l})}this.i=this.b.length},L:function(a,d){var f=this.width/a,e=this.height/d,b,g,k=this.b.length,l=a*d*k,r=new Uint8ClampedArray(l),n=new Uint32Array(a);for(g=0;g<k;g++){var q=this.b[g];var h=q.U*f;var c=q.V*e;var C=g;var w=q.R;var p=q.c+1<<3;for(b=0;b<a;b++)q=0|b*h,n[b]=
- (q&4294967288)<<3|q&7;for(h=0;h<d;h++)for(q=0|h*c,q=p*(q&4294967288)|(q&7)<<3,b=0;b<a;b++)r[C]=w[q+n[b]],C+=k}if(e=this.M)for(g=0;g<l;)for(f=q=0;q<k;q++,g++,f+=2)r[g]=(r[g]*e[f]>>8)+e[f+1];return r},w:function(){return this.A?!!this.A.W:3===this.i?0===this.B?!1:!0:1===this.B?!0:!1},I:function(a){for(var d,f,e,b=0,g=a.length;b<g;b+=3)d=a[b],f=a[b+1],e=a[b+2],a[b]=d-179.456+1.402*e,a[b+1]=d+135.459-.344*f-.714*e,a[b+2]=d-226.816+1.772*f;return a},K:function(a){for(var d,f,e,b,g=0,k=0,l=a.length;k<l;k+=
- 4)d=a[k],f=a[k+1],e=a[k+2],b=a[k+3],a[g++]=-122.67195406894+f*(-6.60635669420364E-5*f+4.37130475926232E-4*e-5.4080610064599E-5*d+4.8449797120281E-4*b-.154362151871126)+e*(-9.57964378445773E-4*e+8.17076911346625E-4*d-.00477271405408747*b+1.53380253221734)+d*(9.61250184130688E-4*d-.00266257332283933*b+.48357088451265)+b*(-3.36197177618394E-4*b+.484791561490776),a[g++]=107.268039397724+f*(2.19927104525741E-5*f-6.40992018297945E-4*e+6.59397001245577E-4*d+4.26105652938837E-4*b-.176491792462875)+e*(-7.78269941513683E-4*
- e+.00130872261408275*d+7.70482631801132E-4*b-.151051492775562)+d*(.00126935368114843*d-.00265090189010898*b+.25802910206845)+b*(-3.18913117588328E-4*b-.213742400323665),a[g++]=-20.810012546947+f*(-5.70115196973677E-4*f-2.63409051004589E-5*e+.0020741088115012*d-.00288260236853442*b+.814272968359295)+e*(-1.53496057440975E-5*e-1.32689043961446E-4*d+5.60833691242812E-4*b-.195152027534049)+d*(.00174418132927582*d-.00255243321439347*b+.116935020465145)+b*(-3.43531996510555E-4*b+.24165260232407);return a.subarray(0,
- g)},J:function(a){for(var d,f,e,b=0,g=a.length;b<g;b+=4)d=a[b],f=a[b+1],e=a[b+2],a[b]=434.456-d-1.402*e,a[b+1]=119.541-d+.344*f+.714*e,a[b+2]=481.816-d-1.772*f;return a},H:function(a){for(var d,f,e,b,g=0,k=1/255,l=0,r=a.length;l<r;l+=4)d=a[l]*k,f=a[l+1]*k,e=a[l+2]*k,b=a[l+3]*k,a[g++]=255+d*(-4.387332384609988*d+54.48615194189176*f+18.82290502165302*e+212.25662451639585*b-285.2331026137004)+f*(1.7149763477362134*f-5.6096736904047315*e-17.873870861415444*b-5.497006427196366)+e*(-2.5217340131683033*
- e-21.248923337353073*b+17.5119270841813)-b*(21.86122147463605*b+189.48180835922747),a[g++]=255+d*(8.841041422036149*d+60.118027045597366*f+6.871425592049007*e+31.159100130055922*b-79.2970844816548)+f*(-15.310361306967817*f+17.575251261109482*e+131.35250912493976*b-190.9453302588951)+e*(4.444339102852739*e+9.8632861493405*b-24.86741582555878)-b*(20.737325471181034*b+187.80453709719578),a[g++]=255+d*(.8842522430003296*d+8.078677503112928*f+30.89978309703729*e-.23883238689178934*b-14.183576799673286)+
- f*(10.49593273432072*f+63.02378494754052*e+50.606957656360734*b-112.23884253719248)+e*(.03296041114873217*e+115.60384449646641*b-193.58209356861505)-b*(22.33816807309886*b+180.12613974708367);return a.subarray(0,g)},getData:function(a,d,f){if(4<this.i)throw new D("Unsupported color mode");a=this.L(a,d);if(1===this.i&&f){f=a.length;d=new Uint8ClampedArray(3*f);for(var e=0,b=0;b<f;b++){var g=a[b];d[e++]=g;d[e++]=g;d[e++]=g}return d}if(3===this.i&&this.w())return this.I(a);if(4===this.i){if(this.w())return f?
- this.K(a):this.J(a);if(f)return this.H(a)}return a}}; UTIF.JpegDecoder=g})()})();
- //UTIF.JpegDecoder = window.JpegDecoder;
- UTIF.encodeImage = function(rgba, w, h, metadata)
- {
- var idf = { "t256":[w], "t257":[h], "t258":[8,8,8,8], "t259":[1], "t262":[2], "t273":[1000], // strips offset
- "t277":[4], "t278":[h], /* rows per strip */ "t279":[w*h*4], // strip byte counts
- "t282":[1], "t283":[1], "t284":[1], "t286":[0], "t287":[0], "t296":[1], "t305": ["Photopea (UTIF.js)"], "t338":[1]
- };
- if (metadata) for (var i in metadata) idf[i] = metadata[i];
-
- var prfx = new Uint8Array(UTIF.encode([idf]));
- var img = new Uint8Array(rgba);
- var data = new Uint8Array(1000+w*h*4);
- for(var i=0; i<prfx.length; i++) data[i] = prfx[i];
- for(var i=0; i<img .length; i++) data[1000+i] = img[i];
- return data.buffer;
- }
- UTIF.encode = function(ifds)
- {
- var data = new Uint8Array(20000), offset = 4, bin = UTIF._binBE;
- data[0]=77; data[1]=77; data[3]=42;
- var ifdo = 8;
- bin.writeUint(data, offset, ifdo); offset+=4;
- for(var i=0; i<ifds.length; i++)
- {
- var noffs = UTIF._writeIFD(bin, data, ifdo, ifds[i]);
- ifdo = noffs[1];
- if(i<ifds.length-1) bin.writeUint(data, noffs[0], ifdo);
- }
- return data.slice(0, ifdo).buffer;
- }
- //UTIF.encode._writeIFD
- UTIF.decode = function(buff)
- {
- UTIF.decode._decodeG3.allow2D = null;
- var data = new Uint8Array(buff), offset = 0;
- var id = UTIF._binBE.readASCII(data, offset, 2); offset+=2;
- var bin = id=="II" ? UTIF._binLE : UTIF._binBE;
- var num = bin.readUshort(data, offset); offset+=2;
- var ifdo = bin.readUint(data, offset); offset+=4;
- var ifds = [];
- while(true)
- {
- var noff = UTIF._readIFD(bin, data, ifdo, ifds);
- //var ifd = ifds[ifds.length-1]; if(ifd["t34665"]) { ifd.exifIFD = []; UTIF._readIFD(bin, data, ifd["t34665"][0], ifd.exifIFD); }
- ifdo = bin.readUint(data, noff);
- if(ifdo==0) break;
- }
- return ifds;
- }
- UTIF.decodeImages = function(buff, ifds)
- {
- var data = new Uint8Array(buff);
- var id = UTIF._binBE.readASCII(data, 0, 2);
- for(var ii=0; ii<ifds.length; ii++)
- {
- var img = ifds[ii];
- if(img["t256"]==null) continue; // EXIF files don't have TIFF tags
- img.isLE = id=="II";
- img.width = img["t256"][0]; //delete img["t256"];
- img.height = img["t257"][0]; //delete img["t257"];
- var cmpr = img["t259"] ? img["t259"][0] : 1; //delete img["t259"];
- var fo = img["t266"] ? img["t266"][0] : 1; //delete img["t266"];
- if(img["t284"] && img["t284"][0]==2) log("PlanarConfiguration 2 should not be used!");
- var bipp = (img["t258"]?Math.min(32,img["t258"][0]):1) * (img["t277"]?img["t277"][0]:1); // bits per pixel
- var bipl = Math.ceil(img.width*bipp/8)*8;
- var soff = img["t273"]; if(soff==null) soff = img["t324"];
- var bcnt = img["t279"]; if(cmpr==1 && soff.length==1) bcnt = [img.height*(bipl>>>3)]; if(bcnt==null) bcnt = img["t325"];
- var bytes = new Uint8Array(img.height*(bipl>>>3)), bilen = 0;
- if(img["t322"]!=null) // tiled
- {
- var tw = img["t322"][0], th = img["t323"][0];
- var tx = Math.floor((img.width + tw - 1) / tw);
- var ty = Math.floor((img.height + th - 1) / th);
- var tbuff = new Uint8Array(Math.ceil(tw*th*bipp/8)|0);
- for(var y=0; y<ty; y++)
- for(var x=0; x<tx; x++)
- {
- var i = y*tx+x; for(var j=0; j<tbuff.length; j++) tbuff[j]=0;
- UTIF.decode._decompress(img, data, soff[i], bcnt[i], cmpr, tbuff, 0, fo);
- // Might be required for 7 too. Need to check
- if (cmpr==6) bytes = tbuff;
- else UTIF._copyTile(tbuff, Math.ceil(tw*bipp/8)|0, th, bytes, Math.ceil(img.width*bipp/8)|0, img.height, Math.ceil(x*tw*bipp/8)|0, y*th);
- }
- bilen = bytes.length*8;
- }
- else // stripped
- {
- var rps = img["t278"] ? img["t278"][0] : img.height; rps = Math.min(rps, img.height);
- for(var i=0; i<soff.length; i++)
- {
- UTIF.decode._decompress(img, data, soff[i], bcnt[i], cmpr, bytes, Math.ceil(bilen/8)|0, fo);
- bilen += bipl * rps;
- }
- bilen = Math.min(bilen, bytes.length*8);
- }
- img.data = new Uint8Array(bytes.buffer, 0, Math.ceil(bilen/8)|0);
- }
- }
- UTIF.decode._decompress = function(img, data, off, len, cmpr, tgt, toff, fo) // fill order
- {
- //console.log("compression", cmpr);
- if(false) {}
- else if(cmpr==1) for(var j=0; j<len; j++) tgt[toff+j] = data[off+j];
- else if(cmpr==3) UTIF.decode._decodeG3 (data, off, len, tgt, toff, img.width, fo);
- else if(cmpr==4) UTIF.decode._decodeG4 (data, off, len, tgt, toff, img.width, fo);
- else if(cmpr==5) UTIF.decode._decodeLZW(data, off, tgt, toff);
- else if(cmpr==6) UTIF.decode._decodeOldJPEG(img, data, off, len, tgt, toff);
- else if(cmpr==7) UTIF.decode._decodeNewJPEG(img, data, off, len, tgt, toff);
- else if(cmpr==8) { var src = new Uint8Array(data.buffer,off,len); var bin = pako["inflate"](src); for(var i=0; i<bin.length; i++) tgt[toff+i]=bin[i]; }
- else if(cmpr==32773) UTIF.decode._decodePackBits(data, off, len, tgt, toff);
- else if(cmpr==32809) UTIF.decode._decodeThunder (data, off, len, tgt, toff);
- //else if(cmpr==34713) UTIF.decode._decodeNikon (data, off, len, tgt, toff);
- else log("Unknown compression", cmpr);
- if(img["t317"] && img["t317"][0]==2)
- {
- var noc = (img["t277"]?img["t277"][0]:1), h = (img["t278"] ? img["t278"][0] : img.height), bpr = img.width*noc;
- //log(noc);
- for(var y=0; y<h; y++)
- {
- var ntoff = toff+y*bpr;
- if(noc==3) for(var j= 3; j<bpr; j+=3)
- {
- tgt[ntoff+j ] = (tgt[ntoff+j ] + tgt[ntoff+j-3])&255;
- tgt[ntoff+j+1] = (tgt[ntoff+j+1] + tgt[ntoff+j-2])&255;
- tgt[ntoff+j+2] = (tgt[ntoff+j+2] + tgt[ntoff+j-1])&255;
- }
- else for(var j=noc; j<bpr; j++) tgt[ntoff+j] = (tgt[ntoff+j] + tgt[ntoff+j-noc])&255;
- }
- }
- }
- UTIF.decode._decodeNikon = function(data, off, len, tgt, toff)
- {
- var nikon_tree = [
- [ 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */
- 5,4,3,6,2,7,1,0,8,9,11,10,12 ],
- [ 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */
- 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 ],
- [ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */
- 5,4,6,3,7,2,8,1,9,0,10,11,12 ],
- [ 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */
- 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 ],
- [ 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */
- 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 ],
- [ 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */
- 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 ] ];
- //struct decode *dindex;
- var ver0, ver1, vpred, hpred, csize;
- var i, min, max, step=0, huff=0, split=0, row, col, len, shl, diff;
- log(data.slice(off,off+100));
- ver0 = data[off]; off++;
- ver1 = data[off]; off++;
- log(ver0.toString(16), ver1.toString(16), len);
- }
- UTIF.decode._decodeNewJPEG = function(img, data, off, len, tgt, toff)
- {
- var tables = img["t347"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len);
-
- if (tables)
- {
- var SOI = 216, EOI = 217, boff = 0;
- for (var i=0; i<(tlen-1); i++)
- {
- // Skip EOI marker from JPEGTables
- if (tables[i]==255 && tables[i+1]==EOI) break;
- buff[boff++] = tables[i];
- }
- // Skip SOI marker from data
- var byte1 = data[off], byte2 = data[off + 1];
- if (byte1!=255 || byte2!=SOI)
- {
- buff[boff++] = byte1;
- buff[boff++] = byte2;
- }
- for (var i=2; i<len; i++) buff[boff++] = data[off+i];
- }
- else for (var i=0; i<len; i++) buff[i] = data[off+i];
- if(img["t262"]==32803) // lossless JPEG (used in DNG files) is not available in JpegDecoder.
- {
- var bps = img["t258"][0], dcdr = new LosslessJpegDecoder();
- var out = dcdr.decode(buff), olen=out.length;
- if(false) {}
- else if(bps==16) for(var i=0; i<olen; i++) { tgt[toff++] = (out[i]&255); tgt[toff++] = (out[i]>>>8); }
- else if(bps==12) for(var i=0; i<olen; i+=2) { tgt[toff++] = (out[i]>>>4); tgt[toff++] = ((out[i]<<4)|(out[i+1]>>>8))&255; tgt[toff++] = out[i+1]&255; }
- else throw new Error("unsupported bit depth "+bps);
- }
- else
- {
- var parser = new UTIF.JpegDecoder(); parser.parse(buff);
- var decoded = parser.getData(parser.width, parser.height);
- for (var i=0; i<decoded.length; i++) tgt[toff + i] = decoded[i];
- }
- // PhotometricInterpretation is 6 (YCbCr) for JPEG, but after decoding we populate data in
- // RGB format, so updating the tag value
- if(img["t262"][0] == 6) img["t262"][0] = 2;
- }
- UTIF.decode._decodeOldJPEGInit = function(img, data, off, len)
- {
- var SOI = 216, EOI = 217, DQT = 219, DHT = 196, DRI = 221, SOF0 = 192, SOS = 218;
- var joff = 0, soff = 0, tables, sosMarker, isTiled = false, i, j, k;
- var jpgIchgFmt = img["t513"], jifoff = jpgIchgFmt ? jpgIchgFmt[0] : 0;
- var jpgIchgFmtLen = img["t514"], jiflen = jpgIchgFmtLen ? jpgIchgFmtLen[0] : 0;
- var soffTag = img["t324"] || img["t273"] || jpgIchgFmt;
- var ycbcrss = img["t530"], ssx = 0, ssy = 0;
- var spp = img["t277"]?img["t277"][0]:1;
- var jpgresint = img["t515"];
- if(soffTag)
- {
- soff = soffTag[0];
- isTiled = (soffTag.length > 1);
- }
- if(!isTiled)
- {
- if(data[off]==255 && data[off+1]==SOI) return { jpegOffset: off };
- if(jpgIchgFmt!=null)
- {
- if(data[off+jifoff]==255 && data[off+jifoff+1]==SOI) joff = off+jifoff;
- else log("JPEGInterchangeFormat does not point to SOI");
- if(jpgIchgFmtLen==null) log("JPEGInterchangeFormatLength field is missing");
- else if(jifoff >= soff || (jifoff+jiflen) <= soff) log("JPEGInterchangeFormatLength field value is invalid");
- if(joff != null) return { jpegOffset: joff };
- }
- }
- if(ycbcrss!=null) { ssx = ycbcrss[0]; ssy = ycbcrss[1]; }
- if(jpgIchgFmt!=null)
- if(jpgIchgFmtLen!=null)
- if(jiflen >= 2 && (jifoff+jiflen) <= soff)
- {
- if(data[off+jifoff+jiflen-2]==255 && data[off+jifoff+jiflen-1]==SOI) tables = new Uint8Array(jiflen-2);
- else tables = new Uint8Array(jiflen);
- for(i=0; i<tables.length; i++) tables[i] = data[off+jifoff+i];
- log("Incorrect JPEG interchange format: using JPEGInterchangeFormat offset to derive tables");
- }
- else log("JPEGInterchangeFormat+JPEGInterchangeFormatLength > offset to first strip or tile");
- if(tables == null)
- {
- var ooff = 0, out = [];
- out[ooff++] = 255; out[ooff++] = SOI;
- var qtables = img["t519"];
- if(qtables==null) throw new Error("JPEGQTables tag is missing");
- for(i=0; i<qtables.length; i++)
- {
- out[ooff++] = 255; out[ooff++] = DQT; out[ooff++] = 0; out[ooff++] = 67; out[ooff++] = i;
- for(j=0; j<64; j++) out[ooff++] = data[off+qtables[i]+j];
- }
- for(k=0; k<2; k++)
- {
- var htables = img[(k == 0) ? "t520" : "t521"];
- if(htables==null) throw new Error(((k == 0) ? "JPEGDCTables" : "JPEGACTables") + " tag is missing");
- for(i=0; i<htables.length; i++)
- {
- out[ooff++] = 255; out[ooff++] = DHT;
- //out[ooff++] = 0; out[ooff++] = 67; out[ooff++] = i;
- var nc = 19;
- for(j=0; j<16; j++) nc += data[off+htables[i]+j];
- out[ooff++] = (nc >>> 8); out[ooff++] = nc & 255;
- out[ooff++] = (i | (k << 4));
- for(j=0; j<16; j++) out[ooff++] = data[off+htables[i]+j];
- for(j=0; j<nc; j++) out[ooff++] = data[off+htables[i]+16+j];
- }
- }
- out[ooff++] = 255; out[ooff++] = SOF0;
- out[ooff++] = 0; out[ooff++] = 8 + 3*spp; out[ooff++] = 8;
- out[ooff++] = (img.height >>> 8) & 255; out[ooff++] = img.height & 255;
- out[ooff++] = (img.width >>> 8) & 255; out[ooff++] = img.width & 255;
- out[ooff++] = spp;
- if(spp==1) { out[ooff++] = 1; out[ooff++] = 17; out[ooff++] = 0; }
- else for(i=0; i<3; i++)
- {
- out[ooff++] = i + 1;
- out[ooff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15));
- out[ooff++] = i;
- }
- if(jpgresint!=null && jpgresint[0]!=0)
- {
- out[ooff++] = 255; out[ooff++] = DRI; out[ooff++] = 0; out[ooff++] = 4;
- out[ooff++] = (jpgresint[0] >>> 8) & 255;
- out[ooff++] = jpgresint[0] & 255;
- }
- tables = new Uint8Array(out);
- }
- var sofpos = -1;
- i = 0;
- while(i < (tables.length - 1)) {
- if(tables[i]==255 && tables[i+1]==SOF0) { sofpos = i; break; }
- i++;
- }
- if(sofpos == -1)
- {
- var tmptab = new Uint8Array(tables.length + 10 + 3*spp);
- tmptab.set(tables);
- var tmpoff = tables.length;
- sofpos = tables.length;
- tables = tmptab;
- tables[tmpoff++] = 255; tables[tmpoff++] = SOF0;
- tables[tmpoff++] = 0; tables[tmpoff++] = 8 + 3*spp; tables[tmpoff++] = 8;
- tables[tmpoff++] = (img.height >>> 8) & 255; tables[tmpoff++] = img.height & 255;
- tables[tmpoff++] = (img.width >>> 8) & 255; tables[tmpoff++] = img.width & 255;
- tables[tmpoff++] = spp;
- if(spp==1) { tables[tmpoff++] = 1; tables[tmpoff++] = 17; tables[tmpoff++] = 0; }
- else for(i=0; i<3; i++)
- {
- tables[tmpoff++] = i + 1;
- tables[tmpoff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15));
- tables[tmpoff++] = i;
- }
- }
- if(data[soff]==255 && data[soff+1]==SOS)
- {
- var soslen = (data[soff+2]<<8) | data[soff+3];
- sosMarker = new Uint8Array(soslen+2);
- sosMarker[0] = data[soff]; sosMarker[1] = data[soff+1]; sosMarker[2] = data[soff+2]; sosMarker[3] = data[soff+3];
- for(i=0; i<(soslen-2); i++) sosMarker[i+4] = data[soff+i+4];
- }
- else
- {
- sosMarker = new Uint8Array(2 + 6 + 2*spp);
- var sosoff = 0;
- sosMarker[sosoff++] = 255; sosMarker[sosoff++] = SOS;
- sosMarker[sosoff++] = 0; sosMarker[sosoff++] = 6 + 2*spp; sosMarker[sosoff++] = spp;
- if(spp==1) { sosMarker[sosoff++] = 1; sosMarker[sosoff++] = 0; }
- else for(i=0; i<3; i++)
- {
- sosMarker[sosoff++] = i+1; sosMarker[sosoff++] = (i << 4) | i;
- }
- sosMarker[sosoff++] = 0; sosMarker[sosoff++] = 63; sosMarker[sosoff++] = 0;
- }
- return { jpegOffset: off, tables: tables, sosMarker: sosMarker, sofPosition: sofpos };
- }
- UTIF.decode._decodeOldJPEG = function(img, data, off, len, tgt, toff)
- {
- var i, dlen, tlen, buff, buffoff;
- var jpegData = UTIF.decode._decodeOldJPEGInit(img, data, off, len);
- if(jpegData.jpegOffset!=null)
- {
- dlen = off+len-jpegData.jpegOffset;
- buff = new Uint8Array(dlen);
- for(i=0; i<dlen; i++) buff[i] = data[jpegData.jpegOffset+i];
- }
- else
- {
- tlen = jpegData.tables.length;
- buff = new Uint8Array(tlen + jpegData.sosMarker.length + len + 2);
- buff.set(jpegData.tables);
- buffoff = tlen;
- buff[jpegData.sofPosition+5] = (img.height >>> 8) & 255; buff[jpegData.sofPosition+6] = img.height & 255;
- buff[jpegData.sofPosition+7] = (img.width >>> 8) & 255; buff[jpegData.sofPosition+8] = img.width & 255;
- if(data[off]!=255 || data[off+1]!=SOS)
- {
- buff.set(jpegData.sosMarker, bufoff);
- bufoff += sosMarker.length;
- }
- for(i=0; i<len; i++) buff[bufoff++] = data[off+i];
- buff[bufoff++] = 255; buff[bufoff++] = EOI;
- }
- var parser = new UTIF.JpegDecoder(); parser.parse(buff);
- var decoded = parser.getData(parser.width, parser.height);
- for (var i=0; i<decoded.length; i++) tgt[toff + i] = decoded[i];
- // PhotometricInterpretation is 6 (YCbCr) for JPEG, but after decoding we populate data in
- // RGB format, so updating the tag value
- if(img["t262"][0] == 6) img["t262"][0] = 2;
- }
- UTIF.decode._decodePackBits = function(data, off, len, tgt, toff)
- {
- var sa = new Int8Array(data.buffer), ta = new Int8Array(tgt.buffer), lim = off+len;
- while(off<lim)
- {
- var n = sa[off]; off++;
- if(n>=0 && n<128) for(var i=0; i< n+1; i++) { ta[toff]=sa[off]; toff++; off++; }
- if(n>=-127 && n<0) { for(var i=0; i<-n+1; i++) { ta[toff]=sa[off]; toff++; } off++; }
- }
- }
- UTIF.decode._decodeThunder = function(data, off, len, tgt, toff)
- {
- var d2 = [ 0, 1, 0, -1 ], d3 = [ 0, 1, 2, 3, 0, -3, -2, -1 ];
- var lim = off+len, qoff = toff*2, px = 0;
- while(off<lim)
- {
- var b = data[off], msk = (b>>>6), n = (b&63); off++;
- if(msk==3) { px=(n&15); tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; }
- if(msk==0) for(var i=0; i<n; i++) { tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; }
- if(msk==2) for(var i=0; i<2; i++) { var d=(n>>>(3*(1-i)))&7; if(d!=4) { px+=d3[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } }
- if(msk==1) for(var i=0; i<3; i++) { var d=(n>>>(2*(2-i)))&3; if(d!=2) { px+=d2[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } }
- }
- }
- UTIF.decode._dmap = { "1":0,"011":1,"000011":2,"0000011":3, "010":-1,"000010":-2,"0000010":-3 };
- UTIF.decode._lens = ( function()
- {
- var addKeys = function(lens, arr, i0, inc) { for(var i=0; i<arr.length; i++) lens[arr[i]] = i0 + i*inc; }
- var termW = "00110101,000111,0111,1000,1011,1100,1110,1111,10011,10100,00111,01000,001000,000011,110100,110101," // 15
- + "101010,101011,0100111,0001100,0001000,0010111,0000011,0000100,0101000,0101011,0010011,0100100,0011000,00000010,00000011,00011010," // 31
- + "00011011,00010010,00010011,00010100,00010101,00010110,00010111,00101000,00101001,00101010,00101011,00101100,00101101,00000100,00000101,00001010," // 47
- + "00001011,01010010,01010011,01010100,01010101,00100100,00100101,01011000,01011001,01011010,01011011,01001010,01001011,00110010,00110011,00110100";
- var termB = "0000110111,010,11,10,011,0011,0010,00011,000101,000100,0000100,0000101,0000111,00000100,00000111,000011000," // 15
- + "0000010111,0000011000,0000001000,00001100111,00001101000,00001101100,00000110111,00000101000,00000010111,00000011000,000011001010,000011001011,000011001100,000011001101,000001101000,000001101001," // 31
- + "000001101010,000001101011,000011010010,000011010011,000011010100,000011010101,000011010110,000011010111,000001101100,000001101101,000011011010,000011011011,000001010100,000001010101,000001010110,000001010111," // 47
- + "000001100100,000001100101,000001010010,000001010011,000000100100,000000110111,000000111000,000000100111,000000101000,000001011000,000001011001,000000101011,000000101100,000001011010,000001100110,000001100111";
- var makeW = "11011,10010,010111,0110111,00110110,00110111,01100100,01100101,01101000,01100111,011001100,011001101,011010010,011010011,011010100,011010101,011010110,"
- + "011010111,011011000,011011001,011011010,011011011,010011000,010011001,010011010,011000,010011011";
- var makeB = "0000001111,000011001000,000011001001,000001011011,000000110011,000000110100,000000110101,0000001101100,0000001101101,0000001001010,0000001001011,0000001001100,"
- + "0000001001101,0000001110010,0000001110011,0000001110100,0000001110101,0000001110110,0000001110111,0000001010010,0000001010011,0000001010100,0000001010101,0000001011010,"
- + "0000001011011,0000001100100,0000001100101";
- var makeA = "00000001000,00000001100,00000001101,000000010010,000000010011,000000010100,000000010101,000000010110,000000010111,000000011100,000000011101,000000011110,000000011111";
- termW = termW.split(","); termB = termB.split(","); makeW = makeW.split(","); makeB = makeB.split(","); makeA = makeA.split(",");
- var lensW = {}, lensB = {};
- addKeys(lensW, termW, 0, 1); addKeys(lensW, makeW, 64,64); addKeys(lensW, makeA, 1792,64);
- addKeys(lensB, termB, 0, 1); addKeys(lensB, makeB, 64,64); addKeys(lensB, makeA, 1792,64);
- return [lensW, lensB];
- } )();
- UTIF.decode._decodeG4 = function(data, off, slen, tgt, toff, w, fo)
- {
- var U = UTIF.decode, boff=off<<3, len=0, wrd=""; // previous starts with 1
- var line=[], pline=[]; for(var i=0; i<w; i++) pline.push(0); pline=U._makeDiff(pline);
- var a0=0, a1=0, a2=0, b1=0, b2=0, clr=0;
- var y=0, mode="", toRead=0;
- var bipl = Math.ceil(w/8)*8;
- while((boff>>>3)<off+slen)
- {
- b1 = U._findDiff(pline, a0+(a0==0?0:1), 1-clr), b2 = U._findDiff(pline, b1, clr); // could be precomputed
- var bit =0;
- if(fo==1) bit = (data[boff>>>3]>>>(7-(boff&7)))&1;
- if(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;
- boff++; wrd+=bit;
- if(mode=="H")
- {
- if(U._lens[clr][wrd]!=null)
- {
- var dl=U._lens[clr][wrd]; wrd=""; len+=dl;
- if(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=""; }
- }
- }
- else
- {
- if(wrd=="0001") { wrd=""; U._addNtimes(line,b2-a0,clr); a0=b2; }
- if(wrd=="001" ) { wrd=""; mode="H"; toRead=2; }
- if(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=""; clr=1-clr; }
- }
- if(line.length==w && mode=="")
- {
- U._writeBits(line, tgt, toff*8+y*bipl);
- clr=0; y++; a0=0;
- pline=U._makeDiff(line); line=[];
- }
- //if(wrd.length>150) { log(wrd); break; throw "e"; }
- }
- }
- UTIF.decode._findDiff = function(line, x, clr) { for(var i=0; i<line.length; i+=2) if(line[i]>=x && line[i+1]==clr) return line[i]; }
- UTIF.decode._makeDiff = function(line)
- {
- var out = []; if(line[0]==1) out.push(0,1);
- for(var i=1; i<line.length; i++) if(line[i-1]!=line[i]) out.push(i, line[i]);
- out.push(line.length,0,line.length,1); return out;
- }
- UTIF.decode._decodeG3 = function(data, off, slen, tgt, toff, w, fo)
- {
- var U = UTIF.decode, boff=off<<3, len=0, wrd="";
- var line=[], pline=[]; for(var i=0; i<w; i++) line.push(0);
- var a0=0, a1=0, a2=0, b1=0, b2=0, clr=0;
- var y=-1, mode="", toRead=0, is1D=false;
- var bipl = Math.ceil(w/8)*8;
- while((boff>>>3)<off+slen)
- {
- b1 = U._findDiff(pline, a0+(a0==0?0:1), 1-clr), b2 = U._findDiff(pline, b1, clr); // could be precomputed
- var bit =0;
- if(fo==1) bit = (data[boff>>>3]>>>(7-(boff&7)))&1;
- if(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;
- boff++; wrd+=bit;
- if(is1D)
- {
- if(U._lens[clr][wrd]!=null)
- {
- var dl=U._lens[clr][wrd]; wrd=""; len+=dl;
- if(dl<64) { U._addNtimes(line,len,clr); clr=1-clr; len=0; }
- }
- }
- else
- {
- if(mode=="H")
- {
- if(U._lens[clr][wrd]!=null)
- {
- var dl=U._lens[clr][wrd]; wrd=""; len+=dl;
- if(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=""; }
- }
- }
- else
- {
- if(wrd=="0001") { wrd=""; U._addNtimes(line,b2-a0,clr); a0=b2; }
- if(wrd=="001" ) { wrd=""; mode="H"; toRead=2; }
- if(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=""; clr=1-clr; }
- }
- }
- if(wrd.endsWith("000000000001")) // needed for some files
- {
- if(y>=0) U._writeBits(line, tgt, toff*8+y*bipl);
- if(fo==1) is1D = ((data[boff>>>3]>>>(7-(boff&7)))&1)==1;
- if(fo==2) is1D = ((data[boff>>>3]>>>( (boff&7)))&1)==1;
- boff++;
- if(U._decodeG3.allow2D==null) U._decodeG3.allow2D=is1D;
- if(!U._decodeG3.allow2D) { is1D = true; boff--; }
- //log("EOL",y, "next 1D:", is1D);
- wrd=""; clr=0; y++; a0=0;
- pline=U._makeDiff(line); line=[];
- }
- }
- if(line.length==w) U._writeBits(line, tgt, toff*8+y*bipl);
- }
- UTIF.decode._addNtimes = function(arr, n, val) { for(var i=0; i<n; i++) arr.push(val); }
- UTIF.decode._writeBits = function(bits, tgt, boff)
- {
- for(var i=0; i<bits.length; i++) tgt[(boff+i)>>>3] |= (bits[i]<<(7-((boff+i)&7)));
- }
- UTIF.decode._decodeLZW = function(data, off, tgt, toff)
- {
- if(UTIF.decode._lzwTab==null)
- {
- var tb=new Uint32Array(0xffff), tn=new Uint16Array(0xffff), chr=new Uint8Array(2e6);
- for(var i=0; i<256; i++) { chr[i<<2]=i; tb[i]=i<<2; tn[i]=1; }
- UTIF.decode._lzwTab = [tb,tn,chr];
- }
- var copy = UTIF.decode._copyData;
- var tab = UTIF.decode._lzwTab[0], tln=UTIF.decode._lzwTab[1], chr=UTIF.decode._lzwTab[2], totl = 258, chrl = 258<<2;
- var bits = 9, boff = off<<3; // offset in bits
- var ClearCode = 256, EoiCode = 257;
- var v = 0, Code = 0, OldCode = 0;
- while(true)
- {
- v = (data[boff>>>3]<<16) | (data[(boff+8)>>>3]<<8) | data[(boff+16)>>>3];
- Code = ( v>>(24-(boff&7)-bits) ) & ((1<<bits)-1); boff+=bits;
- if(Code==EoiCode) break;
- if(Code==ClearCode)
- {
- bits=9; totl = 258; chrl = 258<<2;
- v = (data[boff>>>3]<<16) | (data[(boff+8)>>>3]<<8) | data[(boff+16)>>>3];
- Code = ( v>>(24-(boff&7)-bits) ) & ((1<<bits)-1); boff+=bits;
- if(Code==EoiCode) break;
- tgt[toff]=Code; toff++;
- }
- else if(Code<totl)
- {
- var cd = tab[Code], cl = tln[Code];
- copy(chr,cd,tgt,toff,cl); toff += cl;
- if(OldCode>=totl) { tab[totl] = chrl; chr[tab[totl]] = cd[0]; tln[totl]=1; chrl=(chrl+1+3)&~0x03; totl++; }
- else
- {
- tab[totl] = chrl;
- var nit = tab[OldCode], nil = tln[OldCode];
- copy(chr,nit,chr,chrl,nil);
- chr[chrl+nil]=chr[cd]; nil++;
- tln[totl]=nil; totl++;
- chrl=(chrl+nil+3)&~0x03;
- }
- if(totl+1==(1<<bits)) bits++;
- }
- else
- {
- if(OldCode>=totl) { tab[totl] = chrl; tln[totl]=0; totl++; }
- else
- {
- tab[totl] = chrl;
- var nit = tab[OldCode], nil = tln[OldCode];
- copy(chr,nit,chr,chrl,nil);
- chr[chrl+nil]=chr[chrl]; nil++;
- tln[totl]=nil; totl++;
- copy(chr,chrl,tgt,toff,nil); toff += nil;
- chrl=(chrl+nil+3)&~0x03;
- }
- if(totl+1==(1<<bits)) bits++;
- }
- OldCode = Code;
- }
- }
- UTIF.decode._copyData = function(s,so,t,to,l) { for(var i=0;i<l;i+=4) { t[to+i]=s[so+i]; t[to+i+1]=s[so+i+1]; t[to+i+2]=s[so+i+2]; t[to+i+3]=s[so+i+3]; } }
- UTIF.tags = {254:"NewSubfileType",255:"SubfileType",256:"ImageWidth",257:"ImageLength",258:"BitsPerSample",259:"Compression",262:"PhotometricInterpretation",266:"FillOrder",
- 269:"DocumentName",270:"ImageDescription",271:"Make",272:"Model",273:"StripOffset",274:"Orientation",277:"SamplesPerPixel",278:"RowsPerStrip",
- 279:"StripByteCounts",280:"MinSampleValue",281:"MaxSampleValue",282:"XResolution",283:"YResolution",284:"PlanarConfiguration",285:"PageName",
- 286:"XPosition",287:"YPosition",
- 292:"T4Options",296:"ResolutionUnit",297:"PageNumber",305:"Software",306:"DateTime",
- 315:"Artist",316:"HostComputer",317:"Predictor",318:"WhitePoint",319:"PrimaryChromaticities",320:"ColorMap",
- 321:"HalftoneHints",322:"TileWidth",
- 323:"TileLength",324:"TileOffset",325:"TileByteCounts",330:"SubIFDs",336:"DotRange",338:"ExtraSample",339:"SampleFormat", 347:"JPEGTables",
- 512:"JPEGProc",513:"JPEGInterchangeFormat",514:"JPEGInterchangeFormatLength",519:"JPEGQTables",520:"JPEGDCTables",521:"JPEGACTables",
- 529:"YCbCrCoefficients",530:"YCbCrSubSampling",531:"YCbCrPositioning",532:"ReferenceBlackWhite",700:"XMP",
- 33421:"CFARepeatPatternDim",33422:"CFAPattern",33432:"Copyright",33434:"ExposureTime",33437:"FNumber",33723:"IPTC/NAA",34377:"Photoshop",
- 34665:"ExifIFD",34675:"ICC Profile",34850:"ExposureProgram",34853:"GPSInfo",34855:"ISOSpeedRatings",34858:"TimeZoneOffset",34859:"SelfTimeMode",
- 36867:"DateTimeOriginal",36868:"DateTimeDigitized",
- 37377:"ShutterSpeedValue",37378:"ApertureValue",37380:"ExposureBiasValue",37383:"MeteringMode",37385:"Flash",37386:"FocalLength",
- 37390:"FocalPlaneXResolution",37391:"FocalPlaneYResolution",37392:"FocalPlaneResolutionUnit",37393:"ImageNumber",37398:"TIFF/EPStandardID",37399:"SensingMethod",
- 37500:"MakerNote",37510:"UserComment",37724:"ImageSourceData",
- 40092:"XPComment",40094:"XPKeywords",
- 40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelXDimension",41486:"FocalPlaneXResolution",41487:"FocalPlaneYResolution",41488:"FocalPlaneResolutionUnit",
- 41985:"CustomRendered",41986:"ExposureMode",41987:"WhiteBalance",41990:"SceneCaptureType",
- 50706:"DNGVersion",50707:"DNGBackwardVersion",50708:"UniqueCameraModel",50709:"LocalizedCameraModel",50710:"CFAPlaneColor",
- 50711:"CFALayout",50712:"LinearizationTable",50713:"BlackLevelRepeatDim",50714:"BlackLevel",50716:"BlackLevelDeltaV",50717:"WhiteLevel",
- 50718:"DefaultScale",50719:"DefaultCropOrigin",
- 50720:"DefaultCropSize",50733:"BayerGreenSplit",50738:"AntiAliasStrength",
- 50721:"ColorMatrix1",50722:"ColorMatrix2",50723:"CameraCalibration1",50724:"CameraCalibration2",50727:"AnalogBalance",50728:"AsShotNeutral",
- 50730:"BaselineExposure",50731:"BaselineNoise",50732:"BaselineSharpness",50734:"LinearResponseLimit",50735:"CameraSerialNumber",50736:"LensInfo",50739:"ShadowScale",
- 50740:"DNGPrivateData",50741:"MakerNoteSafety",50778:"CalibrationIlluminant1",50779:"CalibrationIlluminant2",50780:"BestQualityScale",
- 50781:"RawDataUniqueID",50827:"OriginalRawFileName",50829:"ActiveArea",50830:"MaskedAreas",50931:"CameraCalibrationSignature",50932:"ProfileCalibrationSignature",
- 50935:"NoiseReductionApplied",50936:"ProfileName",50937:"ProfileHueSatMapDims",50938:"ProfileHueSatMapData1",50939:"ProfileHueSatMapData2",
- 50940:"ProfileToneCurve",50941:"ProfileEmbedPolicy",50942:"ProfileCopyright",
- 50964:"ForwardMatrix1",50965:"ForwardMatrix2",50966:"PreviewApplicationName",50967:"PreviewApplicationVersion",50969:"PreviewSettingsDigest",
- 50970:"PreviewColorSpace",50971:"PreviewDateTime",50972:"RawImageDigest",
- 51008:"OpcodeList1",51009:"OpcodeList2",51022:"OpcodeList3",51041:"NoiseProfile",51089:"OriginalDefaultFinalSize",
- 51090:"OriginalBestQualityFinalSize",51091:"OriginalDefaultCropSize",51125:"DefaultUserCrop"};
- UTIF.ttypes = { 256:3,257:3,258:3, 259:3, 262:3, 273:4, 274:3, 277:3,278:4,279:4, 282:5, 283:5, 284:3, 286:5,287:5, 296:3, 305:2, 306:2, 338:3, 513:4, 514:4, 34665:4 };
- UTIF._readIFD = function(bin, data, offset, ifds)
- {
- var cnt = bin.readUshort(data, offset); offset+=2;
- var ifd = {}; ifds.push(ifd);
- //log(">>>----------------");
- for(var i=0; i<cnt; i++)
- {
- var tag = bin.readUshort(data, offset); offset+=2;
- var type = bin.readUshort(data, offset); offset+=2;
- var num = bin.readUint (data, offset); offset+=4;
- var voff = bin.readUint (data, offset); offset+=4;
- var arr = [];
- ifd["t"+tag] = arr;
- //ifd["t"+tag+"-"+UTIF.tags[tag]] = arr;
- if(type== 1 || type==7) { for(var j=0; j<num; j++) arr.push(data[(num<5 ? offset-4 : voff)+j]); }
- if(type== 2) { arr.push( bin.readASCII(data, (num<5 ? offset-4 : voff), num-1) ); }
- if(type== 3) { for(var j=0; j<num; j++) arr.push(bin.readUshort(data, (num<3 ? offset-4 : voff)+2*j)); }
- if(type== 4) { for(var j=0; j<num; j++) arr.push(bin.readUint (data, (num<2 ? offset-4 : voff)+4*j)); }
- if(type== 5) { for(var j=0; j<num; j++) arr.push(bin.readUint (data, voff+j*8) / bin.readUint(data,voff+j*8+4)); }
- if(type== 8) { for(var j=0; j<num; j++) arr.push(bin.readShort (data, (num<3 ? offset-4 : voff)+2*j)); }
- if(type== 9) { for(var j=0; j<num; j++) arr.push(bin.readInt (data, (num<2 ? offset-4 : voff)+4*j)); }
- if(type==10) { for(var j=0; j<num; j++) arr.push(bin.readInt (data, voff+j*8) / bin.readInt (data,voff+j*8+4)); }
- if(type==11) { for(var j=0; j<num; j++) arr.push(bin.readFloat (data, voff+j*4)); }
- if(type==12) { for(var j=0; j<num; j++) arr.push(bin.readDouble(data, voff+j*8)); }
- if(num!=0 && arr.length==0) log("unknown TIFF tag type: ", type, "num:",num);
- //log(tag, type, UTIF.tags[tag], arr);
- if(tag==330) for(var j=0; j<num; j++) UTIF._readIFD(bin, data, arr[j], ifds);
- //if(tag==34665) UTIF._readIFD(bin, data, arr[0], ifds);
- }
- //log("<<<---------------");
- return offset;
- }
- UTIF._writeIFD = function(bin, data, offset, ifd)
- {
- var keys = Object.keys(ifd);
- bin.writeUshort(data, offset, keys.length); offset+=2;
- var eoff = offset + keys.length*12 + 4;
- for(var ki=0; ki<keys.length; ki++)
- {
- var key = keys[ki];
- var tag = parseInt(key.slice(1)), type = UTIF.ttypes[tag]; if(type==null) throw new Error("unknown type of tag: "+tag);
- var val = ifd[key]; if(type==2) val=val[0]+"\u0000"; var num = val.length;
- bin.writeUshort(data, offset, tag ); offset+=2;
- bin.writeUshort(data, offset, type); offset+=2;
- bin.writeUint (data, offset, num ); offset+=4;
- var dlen = [-1, 1, 1, 2, 4, 8, 0, 0, 0, 0, 0, 0, 8][type] * num;
- var toff = offset;
- if(dlen>4) { bin.writeUint(data, offset, eoff); toff=eoff; }
- if(type==2) { bin.writeASCII(data, toff, val); }
- if(type==3) { for(var i=0; i<num; i++) bin.writeUshort(data, toff+2*i, val[i]); }
- if(type==4) { for(var i=0; i<num; i++) bin.writeUint (data, toff+4*i, val[i]); }
- if(type==5) { for(var i=0; i<num; i++) { bin.writeUint(data, toff+8*i, Math.round(val[i]*10000)); bin.writeUint(data, toff+8*i+4, 10000); } }
- if (type == 12) { for (var i = 0; i < num; i++) bin.writeDouble(data, toff + 8 * i, val[i]); }
- if(dlen>4) { dlen += (dlen&1); eoff += dlen; }
- offset += 4;
- }
- return [offset, eoff];
- }
- UTIF.toRGBA8 = function(out)
- {
- var w = out.width, h = out.height, area = w*h, qarea = area*4, data = out.data;
- var img = new Uint8Array(area*4);
- // 0: WhiteIsZero, 1: BlackIsZero, 2: RGB, 3: Palette color, 4: Transparency mask, 5: CMYK
- var intp = out["t262"][0], bps = (out["t258"]?Math.min(32,out["t258"][0]):1), isLE = out.isLE ? 1 : 0;
- //log("interpretation: ", intp, "bps", bps, out);
- if(false) {}
- else if(intp==0)
- {
- var bpl = Math.ceil(bps*w/8);
- for(var y=0; y<h; y++) {
- var off = y*bpl, io = y*w;
- if(bps== 1) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=((data[off+(i>>3)])>>(7- (i&7)))& 1; img[qi]=img[qi+1]=img[qi+2]=( 1-px)*255; img[qi+3]=255; }
- if(bps== 4) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=((data[off+(i>>1)])>>(4-4*(i&1)))&15; img[qi]=img[qi+1]=img[qi+2]=(15-px)* 17; img[qi+3]=255; }
- if(bps== 8) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=data[off+i]; img[qi]=img[qi+1]=img[qi+2]=255-px; img[qi+3]=255; }
- }
- }
- else if(intp==1)
- {
- var bpl = Math.ceil(bps*w/8);
- for(var y=0; y<h; y++) {
- var off = y*bpl, io = y*w;
- if(bps== 1) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=((data[off+(i>>3)])>>(7- (i&7)))&1; img[qi]=img[qi+1]=img[qi+2]=(px)*255; img[qi+3]=255; }
- if(bps== 2) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=((data[off+(i>>2)])>>(6-2*(i&3)))&3; img[qi]=img[qi+1]=img[qi+2]=(px)* 85; img[qi+3]=255; }
- if(bps== 8) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=data[off+i]; img[qi]=img[qi+1]=img[qi+2]= px; img[qi+3]=255; }
- if(bps==16) for(var i=0; i<w; i++) { var qi=(io+i)<<2, px=data[off+(2*i+isLE)]; img[qi]=img[qi+1]=img[qi+2]= Math.min(255,px); img[qi+3]=255; } // ladoga.tif
- }
- }
- else if(intp==2)
- {
- if(bps== 8) // this needs to be simplified ... how many channels are there???
- {
- if(out["t338"])
- {
- if(out["t338"][0]>0) for(var i=0; i<qarea; i++) img[i] = data[i]; // sometimes t338 is 1 or 2 in case of Alpha
- else for(var i=0; i<qarea; i+=4) { img[i] = data[i]; img[i+1] = data[i+1]; img[i+2] = data[i+2]; img[i+3] = 255; }
- }
- else
- {
- var smpls = out["t258"]?out["t258"].length : 3;
- if(smpls==4) for(var i=0; i<qarea; i++) img[i] = data[i];
- if(smpls==3) for(var i=0; i< area; i++) { var qi=i<<2, ti=i*3; img[qi]=data[ti]; img[qi+1]=data[ti+1]; img[qi+2]=data[ti+2]; img[qi+3]=255; }
- }
- }
- else // 3x 16-bit channel
- for(var i=0; i<area; i++) { var qi=i<<2, ti=i*6; img[qi]=data[ti]; img[qi+1]=data[ti+2]; img[qi+2]=data[ti+4]; img[qi+3]=255; }
- }
- else if(intp==3)
- {
- var map = out["t320"];
- for(var i=0; i<area; i++) { var qi=i<<2, mi=data[i]; img[qi]=(map[mi]>>8); img[qi+1]=(map[256+mi]>>8); img[qi+2]=(map[512+mi]>>8); img[qi+3]=255; }
- }
- else if(intp==5)
- {
- var smpls = out["t258"]?out["t258"].length : 4;
- var gotAlpha = smpls>4 ? 1 : 0;
- for(var i=0; i<area; i++) {
- var qi=i<<2, si=i*smpls; var C=255-data[si], M=255-data[si+1], Y=255-data[si+2], K=(255-data[si+3])*(1/255);
- img[qi]=~~(C*K+0.5); img[qi+1]=~~(M*K+0.5); img[qi+2]=~~(Y*K+0.5); img[qi+3]=255*(1-gotAlpha)+data[si+4]*gotAlpha;
- }
- }
- else log("Unknown Photometric interpretation: "+intp);
- return img;
- }
- UTIF.replaceIMG = function()
- {
- var imgs = document.getElementsByTagName("img");
- for (var i=0; i<imgs.length; i++)
- {
- var img=imgs[i], src=img.getAttribute("src"); if(src==null) continue;
- var suff=src.split(".").pop().toLowerCase();
- if(suff!="tif" && suff!="tiff") continue;
- var xhr = new XMLHttpRequest(); UTIF._xhrs.push(xhr); UTIF._imgs.push(img);
- xhr.open("GET", src); xhr.responseType = "arraybuffer";
- xhr.onload = UTIF._imgLoaded; xhr.send();
- }
- }
- UTIF._xhrs = []; UTIF._imgs = [];
- UTIF._imgLoaded = function(e)
- {
- var buff = e.target.response;
- var ifds = UTIF.decode(buff), page = ifds[0]; UTIF.decodeImages(buff, ifds);
- var rgba = UTIF.toRGBA8(page), w=page.width, h=page.height;
- var ind = UTIF._xhrs.indexOf(e.target), img = UTIF._imgs[ind];
- UTIF._xhrs.splice(ind,1); UTIF._imgs.splice(ind,1);
- var cnv = document.createElement("canvas"); cnv.width=w; cnv.height=h;
- var ctx = cnv.getContext("2d"), imgd = ctx.createImageData(w,h);
- for(var i=0; i<rgba.length; i++) imgd.data[i]=rgba[i]; ctx.putImageData(imgd,0,0);
- var attr = ["style","class","id"];
- for(var i=0; i<attr.length; i++) cnv.setAttribute(attr[i], img.getAttribute(attr[i]));
- img.parentNode.replaceChild(cnv,img);
- }
- UTIF._binBE =
- {
- nextZero : function(data, o) { while(data[o]!=0) o++; return o; },
- readUshort : function(buff, p) { return (buff[p]<< 8) | buff[p+1]; },
- readShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+1]; a[1]=buff[p+0]; return UTIF._binBE. i16[0]; },
- readInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+3]; a[1]=buff[p+2]; a[2]=buff[p+1]; a[3]=buff[p+0]; return UTIF._binBE. i32[0]; },
- readUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+3]; a[1]=buff[p+2]; a[2]=buff[p+1]; a[3]=buff[p+0]; return UTIF._binBE.ui32[0]; },
- readASCII : function(buff, p, l) { var s = ""; for(var i=0; i<l; i++) s += String.fromCharCode(buff[p+i]); return s; },
- readFloat : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<4;i++) a[i]=buff[p+3-i]; return UTIF._binBE.fl32[0]; },
- readDouble : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<8;i++) a[i]=buff[p+7-i]; return UTIF._binBE.fl64[0]; },
- writeUshort: function(buff, p, n) { buff[p] = (n>> 8)&255; buff[p+1] = n&255; },
- writeUint : function(buff, p, n) { buff[p] = (n>>24)&255; buff[p+1] = (n>>16)&255; buff[p+2] = (n>>8)&255; buff[p+3] = (n>>0)&255; },
- writeASCII : function(buff, p, s) { for(var i = 0; i < s.length; i++) buff[p+i] = s.charCodeAt(i); },
- writeDouble: function(buff, p, n)
- {
- UTIF._binBE.fl64[0] = n;
- for (var i = 0; i < 8; i++) buff[p + i] = UTIF._binBE.ui8[7 - i];
- }
- }
- UTIF._binBE.ui8 = new Uint8Array (8);
- UTIF._binBE.i16 = new Int16Array (UTIF._binBE.ui8.buffer);
- UTIF._binBE.i32 = new Int32Array (UTIF._binBE.ui8.buffer);
- UTIF._binBE.ui32 = new Uint32Array (UTIF._binBE.ui8.buffer);
- UTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer);
- UTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer);
- UTIF._binLE =
- {
- nextZero : UTIF._binBE.nextZero,
- readUshort : function(buff, p) { return (buff[p+1]<< 8) | buff[p]; },
- readShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; return UTIF._binBE. i16[0]; },
- readInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE. i32[0]; },
- readUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE.ui32[0]; },
- readASCII : UTIF._binBE.readASCII,
- readFloat : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<4;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl32[0]; },
- readDouble : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<8;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl64[0]; }
- }
- UTIF._copyTile = function(tb, tw, th, b, w, h, xoff, yoff)
- {
- //log("copyTile", tw, th, w, h, xoff, yoff);
- var xlim = Math.min(tw, w-xoff);
- var ylim = Math.min(th, h-yoff);
- for(var y=0; y<ylim; y++)
- {
- var tof = (yoff+y)*w+xoff;
- var sof = y*tw;
- for(var x=0; x<xlim; x++) b[tof+x] = tb[sof+x];
- }
- }
- })(UTIF, pako);
- })();
- }).call(this,require('_process'))
- },{"_process":312,"pako":265}],362:[function(require,module,exports){
- (function (global){
- /**
- * Module exports.
- */
- module.exports = deprecate;
- /**
- * Mark that a method should not be used.
- * Returns a modified function which warns once by default.
- *
- * If `localStorage.noDeprecation = true` is set, then it is a no-op.
- *
- * If `localStorage.throwDeprecation = true` is set, then deprecated functions
- * will throw an Error when invoked.
- *
- * If `localStorage.traceDeprecation = true` is set, then deprecated functions
- * will invoke `console.trace()` instead of `console.error()`.
- *
- * @param {Function} fn - the function to deprecate
- * @param {String} msg - the string to print to the console when `fn` is invoked
- * @returns {Function} a new "deprecated" version of `fn`
- * @api public
- */
- function deprecate (fn, msg) {
- if (config('noDeprecation')) {
- return fn;
- }
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (config('throwDeprecation')) {
- throw new Error(msg);
- } else if (config('traceDeprecation')) {
- console.trace(msg);
- } else {
- console.warn(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
- return deprecated;
- }
- /**
- * Checks `localStorage` for boolean values for the given `name`.
- *
- * @param {String} name
- * @returns {Boolean}
- * @api private
- */
- function config (name) {
- // accessing global.localStorage can trigger a DOMException in sandboxed iframes
- try {
- if (!global.localStorage) return false;
- } catch (_) {
- return false;
- }
- var val = global.localStorage[name];
- if (null == val) return false;
- return String(val).toLowerCase() === 'true';
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],363:[function(require,module,exports){
- arguments[4][25][0].apply(exports,arguments)
- },{"dup":25}],364:[function(require,module,exports){
- arguments[4][26][0].apply(exports,arguments)
- },{"dup":26}],365:[function(require,module,exports){
- arguments[4][27][0].apply(exports,arguments)
- },{"./support/isBuffer":364,"_process":312,"dup":27,"inherits":363}],366:[function(require,module,exports){
- "use strict";
- var window = require("global/window")
- var isFunction = require("is-function")
- var parseHeaders = require("parse-headers")
- var xtend = require("xtend")
- module.exports = createXHR
- // Allow use of default import syntax in TypeScript
- module.exports.default = createXHR;
- createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
- createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
- forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
- createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
- options = initParams(uri, options, callback)
- options.method = method.toUpperCase()
- return _createXHR(options)
- }
- })
- function forEachArray(array, iterator) {
- for (var i = 0; i < array.length; i++) {
- iterator(array[i])
- }
- }
- function isEmpty(obj){
- for(var i in obj){
- if(obj.hasOwnProperty(i)) return false
- }
- return true
- }
- function initParams(uri, options, callback) {
- var params = uri
- if (isFunction(options)) {
- callback = options
- if (typeof uri === "string") {
- params = {uri:uri}
- }
- } else {
- params = xtend(options, {uri: uri})
- }
- params.callback = callback
- return params
- }
- function createXHR(uri, options, callback) {
- options = initParams(uri, options, callback)
- return _createXHR(options)
- }
- function _createXHR(options) {
- if(typeof options.callback === "undefined"){
- throw new Error("callback argument missing")
- }
- var called = false
- var callback = function cbOnce(err, response, body){
- if(!called){
- called = true
- options.callback(err, response, body)
- }
- }
- function readystatechange() {
- if (xhr.readyState === 4) {
- setTimeout(loadFunc, 0)
- }
- }
- function getBody() {
- // Chrome with requestType=blob throws errors arround when even testing access to responseText
- var body = undefined
- if (xhr.response) {
- body = xhr.response
- } else {
- body = xhr.responseText || getXml(xhr)
- }
- if (isJson) {
- try {
- body = JSON.parse(body)
- } catch (e) {}
- }
- return body
- }
- function errorFunc(evt) {
- clearTimeout(timeoutTimer)
- if(!(evt instanceof Error)){
- evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
- }
- evt.statusCode = 0
- return callback(evt, failureResponse)
- }
- // will load the data & process the response in a special response object
- function loadFunc() {
- if (aborted) return
- var status
- clearTimeout(timeoutTimer)
- if(options.useXDR && xhr.status===undefined) {
- //IE8 CORS GET successful response doesn't have a status field, but body is fine
- status = 200
- } else {
- status = (xhr.status === 1223 ? 204 : xhr.status)
- }
- var response = failureResponse
- var err = null
- if (status !== 0){
- response = {
- body: getBody(),
- statusCode: status,
- method: method,
- headers: {},
- url: uri,
- rawRequest: xhr
- }
- if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
- response.headers = parseHeaders(xhr.getAllResponseHeaders())
- }
- } else {
- err = new Error("Internal XMLHttpRequest Error")
- }
- return callback(err, response, response.body)
- }
- var xhr = options.xhr || null
- if (!xhr) {
- if (options.cors || options.useXDR) {
- xhr = new createXHR.XDomainRequest()
- }else{
- xhr = new createXHR.XMLHttpRequest()
- }
- }
- var key
- var aborted
- var uri = xhr.url = options.uri || options.url
- var method = xhr.method = options.method || "GET"
- var body = options.body || options.data
- var headers = xhr.headers = options.headers || {}
- var sync = !!options.sync
- var isJson = false
- var timeoutTimer
- var failureResponse = {
- body: undefined,
- headers: {},
- statusCode: 0,
- method: method,
- url: uri,
- rawRequest: xhr
- }
- if ("json" in options && options.json !== false) {
- isJson = true
- headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
- if (method !== "GET" && method !== "HEAD") {
- headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
- body = JSON.stringify(options.json === true ? body : options.json)
- }
- }
- xhr.onreadystatechange = readystatechange
- xhr.onload = loadFunc
- xhr.onerror = errorFunc
- // IE9 must have onprogress be set to a unique function.
- xhr.onprogress = function () {
- // IE must die
- }
- xhr.onabort = function(){
- aborted = true;
- }
- xhr.ontimeout = errorFunc
- xhr.open(method, uri, !sync, options.username, options.password)
- //has to be after open
- if(!sync) {
- xhr.withCredentials = !!options.withCredentials
- }
- // Cannot set timeout with sync request
- // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
- // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
- if (!sync && options.timeout > 0 ) {
- timeoutTimer = setTimeout(function(){
- if (aborted) return
- aborted = true//IE9 may still call readystatechange
- xhr.abort("timeout")
- var e = new Error("XMLHttpRequest timeout")
- e.code = "ETIMEDOUT"
- errorFunc(e)
- }, options.timeout )
- }
- if (xhr.setRequestHeader) {
- for(key in headers){
- if(headers.hasOwnProperty(key)){
- xhr.setRequestHeader(key, headers[key])
- }
- }
- } else if (options.headers && !isEmpty(options.headers)) {
- throw new Error("Headers cannot be set on an XDomainRequest object")
- }
- if ("responseType" in options) {
- xhr.responseType = options.responseType
- }
- if ("beforeSend" in options &&
- typeof options.beforeSend === "function"
- ) {
- options.beforeSend(xhr)
- }
- // Microsoft Edge browser sends "undefined" when send is called with undefined value.
- // XMLHttpRequest spec says to pass null as body to indicate no body
- // See https://github.com/naugtur/xhr/issues/100.
- xhr.send(body || null)
- return xhr
- }
- function getXml(xhr) {
- // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
- // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
- try {
- if (xhr.responseType === "document") {
- return xhr.responseXML
- }
- var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
- if (xhr.responseType === "" && !firefoxBugTakenEffect) {
- return xhr.responseXML
- }
- } catch (e) {}
- return null
- }
- function noop() {}
- },{"global/window":251,"is-function":257,"parse-headers":285,"xtend":368}],367:[function(require,module,exports){
- module.exports = (function xmlparser() {
- //common browsers
- if (typeof self.DOMParser !== 'undefined') {
- return function(str) {
- var parser = new self.DOMParser()
- return parser.parseFromString(str, 'application/xml')
- }
- }
- //IE8 fallback
- if (typeof self.ActiveXObject !== 'undefined'
- && new self.ActiveXObject('Microsoft.XMLDOM')) {
- return function(str) {
- var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
- xmlDoc.async = "false"
- xmlDoc.loadXML(str)
- return xmlDoc
- }
- }
- //last resort fallback
- return function(str) {
- var div = document.createElement('div')
- div.innerHTML = str
- return div
- }
- })()
- },{}],368:[function(require,module,exports){
- module.exports = extend
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- function extend() {
- var target = {}
- for (var i = 0; i < arguments.length; i++) {
- var source = arguments[i]
- for (var key in source) {
- if (hasOwnProperty.call(source, key)) {
- target[key] = source[key]
- }
- }
- }
- return target
- }
- },{}],369:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.srcOver = srcOver;
- exports.dstOver = dstOver;
- exports.multiply = multiply;
- exports.screen = screen;
- exports.overlay = overlay;
- exports.darken = darken;
- exports.lighten = lighten;
- exports.hardLight = hardLight;
- exports.difference = difference;
- exports.exclusion = exclusion;
- function srcOver(src, dst) {
- var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- src.a *= ops;
- var a = dst.a + src.a - dst.a * src.a;
- var r = (src.r * src.a + dst.r * dst.a * (1 - src.a)) / a;
- var g = (src.g * src.a + dst.g * dst.a * (1 - src.a)) / a;
- var b = (src.b * src.a + dst.b * dst.a * (1 - src.a)) / a;
- return {
- r: r,
- g: g,
- b: b,
- a: a
- };
- }
- function dstOver(src, dst) {
- var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- src.a *= ops;
- var a = dst.a + src.a - dst.a * src.a;
- var r = (dst.r * dst.a + src.r * src.a * (1 - dst.a)) / a;
- var g = (dst.g * dst.a + src.g * src.a * (1 - dst.a)) / a;
- var b = (dst.b * dst.a + src.b * src.a * (1 - dst.a)) / a;
- return {
- r: r,
- g: g,
- b: b,
- a: a
- };
- }
- function multiply(src, dst) {
- var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- src.a *= ops;
- var a = dst.a + src.a - dst.a * src.a;
- var sra = src.r * src.a;
- var sga = src.g * src.a;
- var sba = src.b * src.a;
- var dra = dst.r * dst.a;
- var dga = dst.g * dst.a;
- var dba = dst.b * dst.a;
- var r = (sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
- var g = (sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
- var b = (sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
- return {
- r: r,
- g: g,
- b: b,
- a: a
- };
- }
- function screen(src, dst) {
- var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- src.a *= ops;
- var a = dst.a + src.a - dst.a * src.a;
- var sra = src.r * src.a;
- var sga = src.g * src.a;
- var sba = src.b * src.a;
- var dra = dst.r * dst.a;
- var dga = dst.g * dst.a;
- var dba = dst.b * dst.a;
- var r = (sra * dst.a + dra * src.a - sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
- var g = (sga * dst.a + dga * src.a - sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
- var b = (sba * dst.a + dba * src.a - sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
- return {
- r: r,
- g: g,
- b: b,
- a: a
- };
- }
- function overlay(src, dst) {
- var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- src.a *= ops;
- var a = dst.a + src.a - dst.a * src.a;
- var sra = src.r * src.a;
- var sga = src.g * src.a;
- var sba = src.b * src.a;
- var dra = dst.r * dst.a;
- var dga = dst.g * dst.a;
- var dba = dst.b * dst.a;
- var r = (2 * dra <= dst.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a;
- var g = (2 * dga <= dst.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a;
- var b = (2 * dba <= dst.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a;
- return {
- r: r,
- g: g,
- b: b,
- a: a
- };
- }
- function darken(src, dst) {
- var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- src.a *= ops;
- var a = dst.a + src.a - dst.a * src.a;
- var sra = src.r * src.a;
- var sga = src.g * src.a;
- var sba = src.b * src.a;
- var dra = dst.r * dst.a;
- var dga = dst.g * dst.a;
- var dba = dst.b * dst.a;
- var r = (Math.min(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
- var g = (Math.min(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
- var b = (Math.min(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
- return {
- r: r,
- g: g,
- b: b,
- a: a
- };
- }
- function lighten(src, dst) {
- var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- src.a *= ops;
- var a = dst.a + src.a - dst.a * src.a;
- var sra = src.r * src.a;
- var sga = src.g * src.a;
- var sba = src.b * src.a;
- var dra = dst.r * dst.a;
- var dga = dst.g * dst.a;
- var dba = dst.b * dst.a;
- var r = (Math.max(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
- var g = (Math.max(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
- var b = (Math.max(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
- return {
- r: r,
- g: g,
- b: b,
- a: a
- };
- }
- function hardLight(src, dst) {
- var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- src.a *= ops;
- var a = dst.a + src.a - dst.a * src.a;
- var sra = src.r * src.a;
- var sga = src.g * src.a;
- var sba = src.b * src.a;
- var dra = dst.r * dst.a;
- var dga = dst.g * dst.a;
- var dba = dst.b * dst.a;
- var r = (2 * sra <= src.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a;
- var g = (2 * sga <= src.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a;
- var b = (2 * sba <= src.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a;
- return {
- r: r,
- g: g,
- b: b,
- a: a
- };
- }
- function difference(src, dst) {
- var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- src.a *= ops;
- var a = dst.a + src.a - dst.a * src.a;
- var sra = src.r * src.a;
- var sga = src.g * src.a;
- var sba = src.b * src.a;
- var dra = dst.r * dst.a;
- var dga = dst.g * dst.a;
- var dba = dst.b * dst.a;
- var r = (sra + dra - 2 * Math.min(sra * dst.a, dra * src.a)) / a;
- var g = (sga + dga - 2 * Math.min(sga * dst.a, dga * src.a)) / a;
- var b = (sba + dba - 2 * Math.min(sba * dst.a, dba * src.a)) / a;
- return {
- r: r,
- g: g,
- b: b,
- a: a
- };
- }
- function exclusion(src, dst) {
- var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- src.a *= ops;
- var a = dst.a + src.a - dst.a * src.a;
- var sra = src.r * src.a;
- var sga = src.g * src.a;
- var sba = src.b * src.a;
- var dra = dst.r * dst.a;
- var dga = dst.g * dst.a;
- var dba = dst.b * dst.a;
- var r = (sra * dst.a + dra * src.a - 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a;
- var g = (sga * dst.a + dga * src.a - 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a;
- var b = (sba * dst.a + dba * src.a - 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a;
- return {
- r: r,
- g: g,
- b: b,
- a: a
- };
- }
- },{}],370:[function(require,module,exports){
- "use strict";
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = composite;
- var _utils = require("@jimp/utils");
- var constants = _interopRequireWildcard(require("../constants"));
- var compositeModes = _interopRequireWildcard(require("./composite-modes"));
- /**
- * Composites a source image over to this image respecting alpha channels
- * @param {Jimp} src the source Jimp instance
- * @param {number} x the x position to blit the image
- * @param {number} y the y position to blit the image
- * @param {object} options determine what mode to use
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- function composite(src, x, y) {
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
- var cb = arguments.length > 4 ? arguments[4] : undefined;
- if (typeof options === 'function') {
- cb = options;
- options = {};
- }
- if (!(src instanceof this.constructor)) {
- return _utils.throwError.call(this, 'The source must be a Jimp image', cb);
- }
- if (typeof x !== 'number' || typeof y !== 'number') {
- return _utils.throwError.call(this, 'x and y must be numbers', cb);
- }
- var _options = options,
- mode = _options.mode,
- opacitySource = _options.opacitySource,
- opacityDest = _options.opacityDest;
- if (!mode) {
- mode = constants.BLEND_SOURCE_OVER;
- }
- if (typeof opacitySource !== 'number' || opacitySource < 0 || opacitySource > 1) {
- opacitySource = 1.0;
- }
- if (typeof opacityDest !== 'number' || opacityDest < 0 || opacityDest > 1) {
- opacityDest = 1.0;
- }
- var blendmode = compositeModes[mode]; // round input
- x = Math.round(x);
- y = Math.round(y);
- var baseImage = this;
- if (opacityDest !== 1.0) {
- baseImage.opacity(opacityDest);
- }
- src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function (sx, sy, idx) {
- var dstIdx = baseImage.getPixelIndex(x + sx, y + sy, constants.EDGE_CROP);
- var blended = blendmode({
- r: this.bitmap.data[idx + 0] / 255,
- g: this.bitmap.data[idx + 1] / 255,
- b: this.bitmap.data[idx + 2] / 255,
- a: this.bitmap.data[idx + 3] / 255
- }, {
- r: baseImage.bitmap.data[dstIdx + 0] / 255,
- g: baseImage.bitmap.data[dstIdx + 1] / 255,
- b: baseImage.bitmap.data[dstIdx + 2] / 255,
- a: baseImage.bitmap.data[dstIdx + 3] / 255
- }, opacitySource);
- baseImage.bitmap.data[dstIdx + 0] = this.constructor.limit255(blended.r * 255);
- baseImage.bitmap.data[dstIdx + 1] = this.constructor.limit255(blended.g * 255);
- baseImage.bitmap.data[dstIdx + 2] = this.constructor.limit255(blended.b * 255);
- baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(blended.a * 255);
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- module.exports = exports.default;
- },{"../constants":371,"./composite-modes":369,"@babel/runtime/helpers/interopRequireWildcard":11,"@jimp/utils":414}],371:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.EDGE_CROP = exports.EDGE_WRAP = exports.EDGE_EXTEND = exports.BLEND_EXCLUSION = exports.BLEND_DIFFERENCE = exports.BLEND_HARDLIGHT = exports.BLEND_LIGHTEN = exports.BLEND_DARKEN = exports.BLEND_OVERLAY = exports.BLEND_SCREEN = exports.BLEND_MULTIPLY = exports.BLEND_DESTINATION_OVER = exports.BLEND_SOURCE_OVER = exports.VERTICAL_ALIGN_BOTTOM = exports.VERTICAL_ALIGN_MIDDLE = exports.VERTICAL_ALIGN_TOP = exports.HORIZONTAL_ALIGN_RIGHT = exports.HORIZONTAL_ALIGN_CENTER = exports.HORIZONTAL_ALIGN_LEFT = exports.AUTO = void 0;
- // used to auto resizing etc.
- var AUTO = -1; // Align modes for cover, contain, bit masks
- exports.AUTO = AUTO;
- var HORIZONTAL_ALIGN_LEFT = 1;
- exports.HORIZONTAL_ALIGN_LEFT = HORIZONTAL_ALIGN_LEFT;
- var HORIZONTAL_ALIGN_CENTER = 2;
- exports.HORIZONTAL_ALIGN_CENTER = HORIZONTAL_ALIGN_CENTER;
- var HORIZONTAL_ALIGN_RIGHT = 4;
- exports.HORIZONTAL_ALIGN_RIGHT = HORIZONTAL_ALIGN_RIGHT;
- var VERTICAL_ALIGN_TOP = 8;
- exports.VERTICAL_ALIGN_TOP = VERTICAL_ALIGN_TOP;
- var VERTICAL_ALIGN_MIDDLE = 16;
- exports.VERTICAL_ALIGN_MIDDLE = VERTICAL_ALIGN_MIDDLE;
- var VERTICAL_ALIGN_BOTTOM = 32; // blend modes
- exports.VERTICAL_ALIGN_BOTTOM = VERTICAL_ALIGN_BOTTOM;
- var BLEND_SOURCE_OVER = 'srcOver';
- exports.BLEND_SOURCE_OVER = BLEND_SOURCE_OVER;
- var BLEND_DESTINATION_OVER = 'dstOver';
- exports.BLEND_DESTINATION_OVER = BLEND_DESTINATION_OVER;
- var BLEND_MULTIPLY = 'multiply';
- exports.BLEND_MULTIPLY = BLEND_MULTIPLY;
- var BLEND_SCREEN = 'screen';
- exports.BLEND_SCREEN = BLEND_SCREEN;
- var BLEND_OVERLAY = 'overlay';
- exports.BLEND_OVERLAY = BLEND_OVERLAY;
- var BLEND_DARKEN = 'darken';
- exports.BLEND_DARKEN = BLEND_DARKEN;
- var BLEND_LIGHTEN = 'lighten';
- exports.BLEND_LIGHTEN = BLEND_LIGHTEN;
- var BLEND_HARDLIGHT = 'hardLight';
- exports.BLEND_HARDLIGHT = BLEND_HARDLIGHT;
- var BLEND_DIFFERENCE = 'difference';
- exports.BLEND_DIFFERENCE = BLEND_DIFFERENCE;
- var BLEND_EXCLUSION = 'exclusion'; // Edge Handling
- exports.BLEND_EXCLUSION = BLEND_EXCLUSION;
- var EDGE_EXTEND = 1;
- exports.EDGE_EXTEND = EDGE_EXTEND;
- var EDGE_WRAP = 2;
- exports.EDGE_WRAP = EDGE_WRAP;
- var EDGE_CROP = 3;
- exports.EDGE_CROP = EDGE_CROP;
- },{}],372:[function(require,module,exports){
- (function (Buffer){
- "use strict";
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- require("core-js/modules/es.array.concat");
- require("core-js/modules/es.array.find");
- require("core-js/modules/es.array.for-each");
- require("core-js/modules/es.array.index-of");
- require("core-js/modules/es.array.iterator");
- require("core-js/modules/es.array.join");
- require("core-js/modules/es.array-buffer.slice");
- require("core-js/modules/es.date.to-string");
- require("core-js/modules/es.number.constructor");
- require("core-js/modules/es.object.assign");
- require("core-js/modules/es.object.entries");
- require("core-js/modules/es.object.to-string");
- require("core-js/modules/es.parse-int");
- require("core-js/modules/es.promise");
- require("core-js/modules/es.regexp.exec");
- require("core-js/modules/es.regexp.to-string");
- require("core-js/modules/es.string.match");
- require("core-js/modules/es.string.replace");
- require("core-js/modules/es.typed-array.uint8-array");
- require("core-js/modules/es.typed-array.uint8-clamped-array");
- require("core-js/modules/es.typed-array.copy-within");
- require("core-js/modules/es.typed-array.every");
- require("core-js/modules/es.typed-array.fill");
- require("core-js/modules/es.typed-array.filter");
- require("core-js/modules/es.typed-array.find");
- require("core-js/modules/es.typed-array.find-index");
- require("core-js/modules/es.typed-array.for-each");
- require("core-js/modules/es.typed-array.includes");
- require("core-js/modules/es.typed-array.index-of");
- require("core-js/modules/es.typed-array.iterator");
- require("core-js/modules/es.typed-array.join");
- require("core-js/modules/es.typed-array.last-index-of");
- require("core-js/modules/es.typed-array.map");
- require("core-js/modules/es.typed-array.reduce");
- require("core-js/modules/es.typed-array.reduce-right");
- require("core-js/modules/es.typed-array.reverse");
- require("core-js/modules/es.typed-array.set");
- require("core-js/modules/es.typed-array.slice");
- require("core-js/modules/es.typed-array.some");
- require("core-js/modules/es.typed-array.sort");
- require("core-js/modules/es.typed-array.subarray");
- require("core-js/modules/es.typed-array.to-locale-string");
- require("core-js/modules/es.typed-array.to-string");
- require("core-js/modules/web.dom-collections.for-each");
- require("core-js/modules/web.timers");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.addConstants = addConstants;
- exports.addJimpMethods = addJimpMethods;
- exports.jimpEvMethod = jimpEvMethod;
- exports.jimpEvChange = jimpEvChange;
- Object.defineProperty(exports, "addType", {
- enumerable: true,
- get: function get() {
- return MIME.addType;
- }
- });
- exports["default"] = void 0;
- var _construct2 = _interopRequireDefault(require("@babel/runtime/helpers/construct"));
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
- var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
- var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
- var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
- var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
- var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
- var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
- var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
- var _fs = _interopRequireDefault(require("fs"));
- var _path = _interopRequireDefault(require("path"));
- var _events = _interopRequireDefault(require("events"));
- var _utils = require("@jimp/utils");
- var _anyBase = _interopRequireDefault(require("any-base"));
- var _mkdirp = _interopRequireDefault(require("mkdirp"));
- var _pixelmatch = _interopRequireDefault(require("pixelmatch"));
- var _tinycolor = _interopRequireDefault(require("tinycolor2"));
- var _phash = _interopRequireDefault(require("./modules/phash"));
- var _request = _interopRequireDefault(require("./request"));
- var _composite = _interopRequireDefault(require("./composite"));
- var _promisify = _interopRequireDefault(require("./utils/promisify"));
- var MIME = _interopRequireWildcard(require("./utils/mime"));
- var _imageBitmap = require("./utils/image-bitmap");
- var constants = _interopRequireWildcard(require("./constants"));
- var alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'; // an array storing the maximum string length of hashes at various bases
- // 0 and 1 do not exist as possible hash lengths
- var maxHashLength = [NaN, NaN];
- for (var i = 2; i < 65; i++) {
- var maxHash = (0, _anyBase["default"])(_anyBase["default"].BIN, alphabet.slice(0, i))(new Array(64 + 1).join('1'));
- maxHashLength.push(maxHash.length);
- } // no operation
- function noop() {} // error checking methods
- function isArrayBuffer(test) {
- return Object.prototype.toString.call(test).toLowerCase().indexOf('arraybuffer') > -1;
- } // Prepare a Buffer object from the arrayBuffer. Necessary in the browser > node conversion,
- // But this function is not useful when running in node directly
- function bufferFromArrayBuffer(arrayBuffer) {
- var buffer = Buffer.alloc(arrayBuffer.byteLength);
- var view = new Uint8Array(arrayBuffer);
- for (var _i = 0; _i < buffer.length; ++_i) {
- buffer[_i] = view[_i];
- }
- return buffer;
- }
- function loadFromURL(options, cb) {
- (0, _request["default"])(options, function (err, response, data) {
- if (err) {
- return cb(err);
- }
- if ('headers' in response && 'location' in response.headers) {
- options.url = response.headers.location;
- return loadFromURL(options, cb);
- }
- if ((0, _typeof2["default"])(data) === 'object' && Buffer.isBuffer(data)) {
- return cb(null, data);
- }
- var msg = 'Could not load Buffer from <' + options.url + '> ' + '(HTTP: ' + response.statusCode + ')';
- return new Error(msg);
- });
- }
- function loadBufferFromPath(src, cb) {
- if (_fs["default"] && typeof _fs["default"].readFile === 'function' && !src.match(/^(http|ftp)s?:\/\/./)) {
- _fs["default"].readFile(src, cb);
- } else {
- loadFromURL({
- url: src
- }, cb);
- }
- }
- function isRawRGBAData(obj) {
- return obj && (0, _typeof2["default"])(obj) === 'object' && typeof obj.width === 'number' && typeof obj.height === 'number' && (Buffer.isBuffer(obj.data) || obj.data instanceof Uint8Array || typeof Uint8ClampedArray === 'function' && obj.data instanceof Uint8ClampedArray) && (obj.data.length === obj.width * obj.height * 4 || obj.data.length === obj.width * obj.height * 3);
- }
- function makeRGBABufferFromRGB(buffer) {
- if (buffer.length % 3 !== 0) {
- throw new Error('Buffer length is incorrect');
- }
- var rgbaBuffer = Buffer.allocUnsafe(buffer.length / 3 * 4);
- var j = 0;
- for (var _i2 = 0; _i2 < buffer.length; _i2++) {
- rgbaBuffer[j] = buffer[_i2];
- if ((_i2 + 1) % 3 === 0) {
- rgbaBuffer[++j] = 255;
- }
- j++;
- }
- return rgbaBuffer;
- }
- var emptyBitmap = {
- data: null,
- width: null,
- height: null
- };
- /**
- * Jimp constructor (from a file)
- * @param path a path to the image
- * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
- */
- /**
- * Jimp constructor (from a url with options)
- * @param options { url, otherOptions}
- * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
- */
- /**
- * Jimp constructor (from another Jimp image or raw image data)
- * @param image a Jimp image to clone
- * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap
- */
- /**
- * Jimp constructor (from a Buffer)
- * @param data a Buffer containing the image data
- * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap
- */
- /**
- * Jimp constructor (to generate a new image)
- * @param w the width of the image
- * @param h the height of the image
- * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
- */
- /**
- * Jimp constructor (to generate a new image)
- * @param w the width of the image
- * @param h the height of the image
- * @param background color to fill the image with
- * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap
- */
- var Jimp =
- /*#__PURE__*/
- function (_EventEmitter) {
- (0, _inherits2["default"])(Jimp, _EventEmitter);
- // An object representing a bitmap in memory, comprising:
- // - data: a buffer of the bitmap data
- // - width: the width of the image in pixels
- // - height: the height of the image in pixels
- // Default colour to use for new pixels
- // Default MIME is PNG
- // Exif data for the image
- // Whether Transparency supporting formats will be exported as RGB or RGBA
- function Jimp() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- (0, _classCallCheck2["default"])(this, Jimp);
- _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Jimp).call(this));
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "bitmap", emptyBitmap);
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_background", 0x00000000);
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_originalMime", Jimp.MIME_PNG);
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_exif", null);
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_rgba", true);
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "writeAsync", function (path) {
- return (0, _promisify["default"])(_this.write, (0, _assertThisInitialized2["default"])(_this), path);
- });
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getBase64Async", function (mime) {
- return (0, _promisify["default"])(_this.getBase64, (0, _assertThisInitialized2["default"])(_this), mime);
- });
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getBuffer", _imageBitmap.getBuffer);
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getBufferAsync", _imageBitmap.getBufferAsync);
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getPixelColour", _this.getPixelColor);
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "setPixelColour", _this.setPixelColor);
- var jimpInstance = (0, _assertThisInitialized2["default"])(_this);
- var cb = noop;
- if (isArrayBuffer(args[0])) {
- args[0] = bufferFromArrayBuffer(args[0]);
- }
- function finish() {
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- args[_key2] = arguments[_key2];
- }
- var err = args[0];
- var evData = err || {};
- evData.methodName = 'constructor';
- setTimeout(function () {
- var _cb;
- // run on next tick.
- if (err && cb === noop) {
- jimpInstance.emitError('constructor', err);
- } else if (!err) {
- jimpInstance.emitMulti('constructor', 'initialized');
- }
- (_cb = cb).call.apply(_cb, [jimpInstance].concat(args));
- }, 1);
- }
- if (typeof args[0] === 'number' && typeof args[1] === 'number' || parseInt(args[0], 10) && parseInt(args[1], 10)) {
- // create a new image
- var w = parseInt(args[0], 10);
- var h = parseInt(args[1], 10);
- cb = args[2]; // with a hex color
- if (typeof args[2] === 'number') {
- _this._background = args[2];
- cb = args[3];
- } // with a css color
- if (typeof args[2] === 'string') {
- _this._background = Jimp.cssColorToHex(args[2]);
- cb = args[3];
- }
- if (typeof cb === 'undefined') {
- cb = noop;
- }
- if (typeof cb !== 'function') {
- return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish));
- }
- _this.bitmap = {
- data: Buffer.alloc(w * h * 4),
- width: w,
- height: h
- };
- for (var _i3 = 0; _i3 < _this.bitmap.data.length; _i3 += 4) {
- _this.bitmap.data.writeUInt32BE(_this._background, _i3);
- }
- finish(null, (0, _assertThisInitialized2["default"])(_this));
- } else if ((0, _typeof2["default"])(args[0]) === 'object' && args[0].url) {
- cb = args[1] || noop;
- if (typeof cb !== 'function') {
- return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish));
- }
- loadFromURL(args[0], function (err, data) {
- if (err) {
- return _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), err, finish);
- }
- _this.parseBitmap(data, args[0].url, finish);
- });
- } else if (args[0] instanceof Jimp) {
- // clone an existing Jimp
- var original = args[0];
- cb = args[1];
- if (typeof cb === 'undefined') {
- cb = noop;
- }
- if (typeof cb !== 'function') {
- return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish));
- }
- _this.bitmap = {
- data: Buffer.from(original.bitmap.data),
- width: original.bitmap.width,
- height: original.bitmap.height
- };
- _this._quality = original._quality;
- _this._deflateLevel = original._deflateLevel;
- _this._deflateStrategy = original._deflateStrategy;
- _this._filterType = original._filterType;
- _this._rgba = original._rgba;
- _this._background = original._background;
- _this._originalMime = original._originalMime;
- finish(null, (0, _assertThisInitialized2["default"])(_this));
- } else if (isRawRGBAData(args[0])) {
- var imageData = args[0];
- cb = args[1] || noop;
- var isRGBA = imageData.width * imageData.height * 4 === imageData.data.length;
- var buffer = isRGBA ? Buffer.from(imageData.data) : makeRGBABufferFromRGB(imageData.data);
- _this.bitmap = {
- data: buffer,
- width: imageData.width,
- height: imageData.height
- };
- finish(null, (0, _assertThisInitialized2["default"])(_this));
- } else if (typeof args[0] === 'string') {
- // read from a path
- var path = args[0];
- cb = args[1];
- if (typeof cb === 'undefined') {
- cb = noop;
- }
- if (typeof cb !== 'function') {
- return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish));
- }
- loadBufferFromPath(path, function (err, data) {
- if (err) {
- return _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), err, finish);
- }
- _this.parseBitmap(data, path, finish);
- });
- } else if ((0, _typeof2["default"])(args[0]) === 'object' && Buffer.isBuffer(args[0])) {
- // read from a buffer
- var data = args[0];
- cb = args[1];
- if (typeof cb !== 'function') {
- return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish));
- }
- _this.parseBitmap(data, null, finish);
- } else {
- // Allow client libs to add new ways to build a Jimp object.
- // Extra constructors must be added by `Jimp.appendConstructorOption()`
- cb = args[args.length - 1];
- if (typeof cb !== 'function') {
- // TODO: try to solve the args after cb problem.
- cb = args[args.length - 2];
- if (typeof cb !== 'function') {
- cb = noop;
- }
- }
- var extraConstructor = Jimp.__extraConstructors.find(function (c) {
- return c.test.apply(c, args);
- });
- if (extraConstructor) {
- new Promise(function (resolve, reject) {
- var _extraConstructor$run;
- return (_extraConstructor$run = extraConstructor.run).call.apply(_extraConstructor$run, [(0, _assertThisInitialized2["default"])(_this), resolve, reject].concat(args));
- }).then(function () {
- return finish(null, (0, _assertThisInitialized2["default"])(_this));
- })["catch"](finish);
- } else {
- return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'No matching constructor overloading was found. ' + 'Please see the docs for how to call the Jimp constructor.', finish));
- }
- }
- return _this;
- }
- /**
- * Parse a bitmap with the loaded image types.
- *
- * @param {Buffer} data raw image data
- * @param {string} path optional path to file
- * @param {function(Error, Jimp)} finish (optional) a callback for when complete
- * @memberof Jimp
- */
- (0, _createClass2["default"])(Jimp, [{
- key: "parseBitmap",
- value: function parseBitmap(data, path, finish) {
- _imageBitmap.parseBitmap.call(this, data, null, finish);
- }
- /**
- * Sets the type of the image (RGB or RGBA) when saving in a format that supports transparency (default is RGBA)
- * @param {boolean} bool A Boolean, true to use RGBA or false to use RGB
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- }, {
- key: "rgba",
- value: function rgba(bool, cb) {
- if (typeof bool !== 'boolean') {
- return _utils.throwError.call(this, 'bool must be a boolean, true for RGBA or false for RGB', cb);
- }
- this._rgba = bool;
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- /**
- * Emit for multiple listeners
- * @param {string} methodName name of the method to emit an error for
- * @param {string} eventName name of the eventName to emit an error for
- * @param {object} data to emit
- */
- }, {
- key: "emitMulti",
- value: function emitMulti(methodName, eventName) {
- var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- data = Object.assign(data, {
- methodName: methodName,
- eventName: eventName
- });
- this.emit('any', data);
- if (methodName) {
- this.emit(methodName, data);
- }
- this.emit(eventName, data);
- }
- }, {
- key: "emitError",
- value: function emitError(methodName, err) {
- this.emitMulti(methodName, 'error', err);
- }
- /**
- * Get the current height of the image
- * @return {number} height of the image
- */
- }, {
- key: "getHeight",
- value: function getHeight() {
- return this.bitmap.height;
- }
- /**
- * Get the current width of the image
- * @return {number} width of the image
- */
- }, {
- key: "getWidth",
- value: function getWidth() {
- return this.bitmap.width;
- }
- /**
- * Nicely format Jimp object when sent to the console e.g. console.log(image)
- * @returns {string} pretty printed
- */
- }, {
- key: "inspect",
- value: function inspect() {
- return '<Jimp ' + (this.bitmap === emptyBitmap ? 'pending...' : this.bitmap.width + 'x' + this.bitmap.height) + '>';
- }
- /**
- * Nicely format Jimp object when converted to a string
- * @returns {string} pretty printed
- */
- }, {
- key: "toString",
- value: function toString() {
- return '[object Jimp]';
- }
- /**
- * Returns the original MIME of the image (default: "image/png")
- * @returns {string} the MIME
- */
- }, {
- key: "getMIME",
- value: function getMIME() {
- var mime = this._originalMime || Jimp.MIME_PNG;
- return mime;
- }
- /**
- * Returns the appropriate file extension for the original MIME of the image (default: "png")
- * @returns {string} the file extension
- */
- }, {
- key: "getExtension",
- value: function getExtension() {
- var mime = this.getMIME();
- return MIME.getExtension(mime);
- }
- /**
- * Writes the image to a file
- * @param {string} path a path to the destination file
- * @param {function(Error, Jimp)} cb (optional) a function to call when the image is saved to disk
- * @returns {Jimp} this for chaining of methods
- */
- }, {
- key: "write",
- value: function write(path, cb) {
- var _this2 = this;
- if (!_fs["default"] || !_fs["default"].createWriteStream) {
- throw new Error('Cant access the filesystem. You can use the getBase64 method.');
- }
- if (typeof path !== 'string') {
- return _utils.throwError.call(this, 'path must be a string', cb);
- }
- if (typeof cb === 'undefined') {
- cb = noop;
- }
- if (typeof cb !== 'function') {
- return _utils.throwError.call(this, 'cb must be a function', cb);
- }
- var mime = MIME.getType(path) || this.getMIME();
- var pathObj = _path["default"].parse(path);
- if (pathObj.dir) {
- _mkdirp["default"].sync(pathObj.dir);
- }
- this.getBuffer(mime, function (err, buffer) {
- if (err) {
- return _utils.throwError.call(_this2, err, cb);
- }
- var stream = _fs["default"].createWriteStream(path);
- stream.on('open', function () {
- stream.write(buffer);
- stream.end();
- }).on('error', function (err) {
- return _utils.throwError.call(_this2, err, cb);
- });
- stream.on('finish', function () {
- cb.call(_this2, null, _this2);
- });
- });
- return this;
- }
- }, {
- key: "getBase64",
- /**
- * Converts the image to a base 64 string
- * @param {string} mime the mime type of the image data to be created
- * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument
- * @returns {Jimp} this for chaining of methods
- */
- value: function getBase64(mime, cb) {
- if (mime === Jimp.AUTO) {
- // allow auto MIME detection
- mime = this.getMIME();
- }
- if (typeof mime !== 'string') {
- return _utils.throwError.call(this, 'mime must be a string', cb);
- }
- if (typeof cb !== 'function') {
- return _utils.throwError.call(this, 'cb must be a function', cb);
- }
- this.getBuffer(mime, function (err, data) {
- if (err) {
- return _utils.throwError.call(this, err, cb);
- }
- var src = 'data:' + mime + ';base64,' + data.toString('base64');
- cb.call(this, null, src);
- });
- return this;
- }
- }, {
- key: "hash",
- /**
- * Generates a perceptual hash of the image <https://en.wikipedia.org/wiki/Perceptual_hashing>. And pads the string. Can configure base.
- * @param {number} base (optional) a number between 2 and 64 representing the base for the hash (e.g. 2 is binary, 10 is decimal, 16 is hex, 64 is base 64). Defaults to 64.
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {string} a string representing the hash
- */
- value: function hash(base, cb) {
- base = base || 64;
- if (typeof base === 'function') {
- cb = base;
- base = 64;
- }
- if (typeof base !== 'number') {
- return _utils.throwError.call(this, 'base must be a number', cb);
- }
- if (base < 2 || base > 64) {
- return _utils.throwError.call(this, 'base must be a number between 2 and 64', cb);
- }
- var hash = this.pHash();
- hash = (0, _anyBase["default"])(_anyBase["default"].BIN, alphabet.slice(0, base))(hash);
- while (hash.length < maxHashLength[base]) {
- hash = '0' + hash; // pad out with leading zeros
- }
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, hash);
- }
- return hash;
- }
- /**
- * Calculates the perceptual hash
- * @returns {number} the perceptual hash
- */
- }, {
- key: "pHash",
- value: function pHash() {
- var pHash = new _phash["default"]();
- return pHash.getHash(this);
- }
- /**
- * Calculates the hamming distance of the current image and a hash based on their perceptual hash
- * @param {hash} compareHash hash to compare to
- * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical
- */
- }, {
- key: "distanceFromHash",
- value: function distanceFromHash(compareHash) {
- var pHash = new _phash["default"]();
- var currentHash = pHash.getHash(this);
- return pHash.distance(currentHash, compareHash);
- }
- /**
- * Converts the image to a buffer
- * @param {string} mime the mime type of the image buffer to be created
- * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument
- * @returns {Jimp} this for chaining of methods
- */
- }, {
- key: "getPixelIndex",
- /**
- * Returns the offset of a pixel in the bitmap buffer
- * @param {number} x the x coordinate
- * @param {number} y the y coordinate
- * @param {string} edgeHandling (optional) define how to sum pixels from outside the border
- * @param {number} cb (optional) a callback for when complete
- * @returns {number} the index of the pixel or -1 if not found
- */
- value: function getPixelIndex(x, y, edgeHandling, cb) {
- var xi;
- var yi;
- if (typeof edgeHandling === 'function' && typeof cb === 'undefined') {
- cb = edgeHandling;
- edgeHandling = null;
- }
- if (!edgeHandling) {
- edgeHandling = Jimp.EDGE_EXTEND;
- }
- if (typeof x !== 'number' || typeof y !== 'number') {
- return _utils.throwError.call(this, 'x and y must be numbers', cb);
- } // round input
- x = Math.round(x);
- y = Math.round(y);
- xi = x;
- yi = y;
- if (edgeHandling === Jimp.EDGE_EXTEND) {
- if (x < 0) xi = 0;
- if (x >= this.bitmap.width) xi = this.bitmap.width - 1;
- if (y < 0) yi = 0;
- if (y >= this.bitmap.height) yi = this.bitmap.height - 1;
- }
- if (edgeHandling === Jimp.EDGE_WRAP) {
- if (x < 0) {
- xi = this.bitmap.width + x;
- }
- if (x >= this.bitmap.width) {
- xi = x % this.bitmap.width;
- }
- if (y < 0) {
- xi = this.bitmap.height + y;
- }
- if (y >= this.bitmap.height) {
- yi = y % this.bitmap.height;
- }
- }
- var i = this.bitmap.width * yi + xi << 2; // if out of bounds index is -1
- if (xi < 0 || xi >= this.bitmap.width) {
- i = -1;
- }
- if (yi < 0 || yi >= this.bitmap.height) {
- i = -1;
- }
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, i);
- }
- return i;
- }
- /**
- * Returns the hex colour value of a pixel
- * @param {number} x the x coordinate
- * @param {number} y the y coordinate
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {number} the color of the pixel
- */
- }, {
- key: "getPixelColor",
- value: function getPixelColor(x, y, cb) {
- if (typeof x !== 'number' || typeof y !== 'number') return _utils.throwError.call(this, 'x and y must be numbers', cb); // round input
- x = Math.round(x);
- y = Math.round(y);
- var idx = this.getPixelIndex(x, y);
- var hex = this.bitmap.data.readUInt32BE(idx);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, hex);
- }
- return hex;
- }
- }, {
- key: "setPixelColor",
- /**
- * Returns the hex colour value of a pixel
- * @param {number} hex color to set
- * @param {number} x the x coordinate
- * @param {number} y the y coordinate
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {number} the index of the pixel or -1 if not found
- */
- value: function setPixelColor(hex, x, y, cb) {
- if (typeof hex !== 'number' || typeof x !== 'number' || typeof y !== 'number') return _utils.throwError.call(this, 'hex, x and y must be numbers', cb); // round input
- x = Math.round(x);
- y = Math.round(y);
- var idx = this.getPixelIndex(x, y);
- this.bitmap.data.writeUInt32BE(hex, idx);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- }, {
- key: "hasAlpha",
- /**
- * Determine if the image contains opaque pixels.
- * @return {boolean} hasAlpha whether the image contains opaque pixels
- */
- value: function hasAlpha() {
- for (var yIndex = 0; yIndex < this.bitmap.height; yIndex++) {
- for (var xIndex = 0; xIndex < this.bitmap.width; xIndex++) {
- var idx = this.bitmap.width * yIndex + xIndex << 2;
- var alpha = this.bitmap.data[idx + 3];
- if (alpha !== 0xff) {
- return true;
- }
- }
- }
- return false;
- }
- /**
- * Iterate scan through a region of the bitmap
- * @param {number} x the x coordinate to begin the scan at
- * @param {number} y the y coordinate to begin the scan at
- * @param w the width of the scan region
- * @param h the height of the scan region
- * @returns {IterableIterator<{x: number, y: number, idx: number, image: Jimp}>}
- */
- }, {
- key: "scanIterator",
- value: function scanIterator(x, y, w, h) {
- if (typeof x !== 'number' || typeof y !== 'number') {
- return _utils.throwError.call(this, 'x and y must be numbers');
- }
- if (typeof w !== 'number' || typeof h !== 'number') {
- return _utils.throwError.call(this, 'w and h must be numbers');
- }
- return (0, _utils.scanIterator)(this, x, y, w, h);
- }
- }]);
- return Jimp;
- }(_events["default"]);
- function addConstants(constants) {
- var jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp;
- Object.entries(constants).forEach(function (_ref) {
- var _ref2 = (0, _slicedToArray2["default"])(_ref, 2),
- name = _ref2[0],
- value = _ref2[1];
- jimpInstance[name] = value;
- });
- }
- function addJimpMethods(methods) {
- var jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp;
- Object.entries(methods).forEach(function (_ref3) {
- var _ref4 = (0, _slicedToArray2["default"])(_ref3, 2),
- name = _ref4[0],
- value = _ref4[1];
- jimpInstance.prototype[name] = value;
- });
- }
- addConstants(constants);
- addJimpMethods({
- composite: _composite["default"]
- });
- Jimp.__extraConstructors = [];
- /**
- * Allow client libs to add new ways to build a Jimp object.
- * @param {string} name identify the extra constructor.
- * @param {function} test a function that returns true when it accepts the arguments passed to the main constructor.
- * @param {function} run where the magic happens.
- */
- Jimp.appendConstructorOption = function (name, test, run) {
- Jimp.__extraConstructors.push({
- name: name,
- test: test,
- run: run
- });
- };
- /**
- * Read an image from a file or a Buffer. Takes the same args as the constructor
- * @returns {Promise} a promise
- */
- Jimp.read = function () {
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
- args[_key3] = arguments[_key3];
- }
- return new Promise(function (resolve, reject) {
- (0, _construct2["default"])(Jimp, args.concat([function (err, image) {
- if (err) reject(err);else resolve(image);
- }]));
- });
- };
- Jimp.create = Jimp.read;
- /**
- * A static helper method that converts RGBA values to a single integer value
- * @param {number} r the red value (0-255)
- * @param {number} g the green value (0-255)
- * @param {number} b the blue value (0-255)
- * @param {number} a the alpha value (0-255)
- * @param {function(Error, Jimp)} cb (optional) A callback for when complete
- * @returns {number} an single integer colour value
- */
- Jimp.rgbaToInt = function (r, g, b, a, cb) {
- if (typeof r !== 'number' || typeof g !== 'number' || typeof b !== 'number' || typeof a !== 'number') {
- return _utils.throwError.call(this, 'r, g, b and a must be numbers', cb);
- }
- if (r < 0 || r > 255) {
- return _utils.throwError.call(this, 'r must be between 0 and 255', cb);
- }
- if (g < 0 || g > 255) {
- _utils.throwError.call(this, 'g must be between 0 and 255', cb);
- }
- if (b < 0 || b > 255) {
- return _utils.throwError.call(this, 'b must be between 0 and 255', cb);
- }
- if (a < 0 || a > 255) {
- return _utils.throwError.call(this, 'a must be between 0 and 255', cb);
- }
- r = Math.round(r);
- b = Math.round(b);
- g = Math.round(g);
- a = Math.round(a);
- var i = r * Math.pow(256, 3) + g * Math.pow(256, 2) + b * Math.pow(256, 1) + a * Math.pow(256, 0);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, i);
- }
- return i;
- };
- /**
- * A static helper method that converts RGBA values to a single integer value
- * @param {number} i a single integer value representing an RGBA colour (e.g. 0xFF0000FF for red)
- * @param {function(Error, Jimp)} cb (optional) A callback for when complete
- * @returns {object} an object with the properties r, g, b and a representing RGBA values
- */
- Jimp.intToRGBA = function (i, cb) {
- if (typeof i !== 'number') {
- return _utils.throwError.call(this, 'i must be a number', cb);
- }
- var rgba = {};
- rgba.r = Math.floor(i / Math.pow(256, 3));
- rgba.g = Math.floor((i - rgba.r * Math.pow(256, 3)) / Math.pow(256, 2));
- rgba.b = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2)) / Math.pow(256, 1));
- rgba.a = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2) - rgba.b * Math.pow(256, 1)) / Math.pow(256, 0));
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, rgba);
- }
- return rgba;
- };
- /**
- * Converts a css color (Hex, 8-digit (RGBA) Hex, RGB, RGBA, HSL, HSLA, HSV, HSVA, Named) to a hex number
- * @param {string} cssColor a number
- * @returns {number} a hex number representing a color
- */
- Jimp.cssColorToHex = function (cssColor) {
- cssColor = cssColor || 0; // 0, null, undefined, NaN
- if (typeof cssColor === 'number') return Number(cssColor);
- return parseInt((0, _tinycolor["default"])(cssColor).toHex8(), 16);
- };
- /**
- * Limits a number to between 0 or 255
- * @param {number} n a number
- * @returns {number} the number limited to between 0 or 255
- */
- Jimp.limit255 = function (n) {
- n = Math.max(n, 0);
- n = Math.min(n, 255);
- return n;
- };
- /**
- * Diffs two images and returns
- * @param {Jimp} img1 a Jimp image to compare
- * @param {Jimp} img2 a Jimp image to compare
- * @param {number} threshold (optional) a number, 0 to 1, the smaller the value the more sensitive the comparison (default: 0.1)
- * @returns {object} an object { percent: percent similar, diff: a Jimp image highlighting differences }
- */
- Jimp.diff = function (img1, img2) {
- var threshold = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.1;
- if (!(img1 instanceof Jimp) || !(img2 instanceof Jimp)) return _utils.throwError.call(this, 'img1 and img2 must be an Jimp images');
- var bmp1 = img1.bitmap;
- var bmp2 = img2.bitmap;
- if (bmp1.width !== bmp2.width || bmp1.height !== bmp2.height) {
- if (bmp1.width * bmp1.height > bmp2.width * bmp2.height) {
- // img1 is bigger
- img1 = img1.cloneQuiet().resize(bmp2.width, bmp2.height);
- } else {
- // img2 is bigger (or they are the same in area)
- img2 = img2.cloneQuiet().resize(bmp1.width, bmp1.height);
- }
- }
- if (typeof threshold !== 'number' || threshold < 0 || threshold > 1) {
- return _utils.throwError.call(this, 'threshold must be a number between 0 and 1');
- }
- var diff = new Jimp(bmp1.width, bmp1.height, 0xffffffff);
- var numDiffPixels = (0, _pixelmatch["default"])(bmp1.data, bmp2.data, diff.bitmap.data, diff.bitmap.width, diff.bitmap.height, {
- threshold: threshold
- });
- return {
- percent: numDiffPixels / (diff.bitmap.width * diff.bitmap.height),
- image: diff
- };
- };
- /**
- * Calculates the hamming distance of two images based on their perceptual hash
- * @param {Jimp} img1 a Jimp image to compare
- * @param {Jimp} img2 a Jimp image to compare
- * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical
- */
- Jimp.distance = function (img1, img2) {
- var phash = new _phash["default"]();
- var hash1 = phash.getHash(img1);
- var hash2 = phash.getHash(img2);
- return phash.distance(hash1, hash2);
- };
- /**
- * Calculates the hamming distance of two images based on their perceptual hash
- * @param {hash} hash1 a pHash
- * @param {hash} hash2 a pHash
- * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical
- */
- Jimp.compareHashes = function (hash1, hash2) {
- var phash = new _phash["default"]();
- return phash.distance(hash1, hash2);
- };
- /**
- * Compute color difference
- * 0 means no difference, 1 means maximum difference.
- * @param {number} rgba1: first color to compare.
- * @param {number} rgba2: second color to compare.
- * Both parameters must be an color object {r:val, g:val, b:val, a:val}
- * Where `a` is optional and `val` is an integer between 0 and 255.
- * @returns {number} float between 0 and 1.
- */
- Jimp.colorDiff = function (rgba1, rgba2) {
- var pow = function pow(n) {
- return Math.pow(n, 2);
- };
- var max = Math.max;
- var maxVal = 255 * 255 * 3;
- if (rgba1.a !== 0 && !rgba1.a) {
- rgba1.a = 255;
- }
- if (rgba2.a !== 0 && !rgba2.a) {
- rgba2.a = 255;
- }
- return (max(pow(rgba1.r - rgba2.r), pow(rgba1.r - rgba2.r - rgba1.a + rgba2.a)) + max(pow(rgba1.g - rgba2.g), pow(rgba1.g - rgba2.g - rgba1.a + rgba2.a)) + max(pow(rgba1.b - rgba2.b), pow(rgba1.b - rgba2.b - rgba1.a + rgba2.a))) / maxVal;
- };
- /**
- * Helper to create Jimp methods that emit events before and after its execution.
- * @param {string} methodName The name to be appended to Jimp prototype.
- * @param {string} evName The event name to be called.
- * It will be prefixed by `before-` and emitted when on method call.
- * It will be appended by `ed` and emitted after the method run.
- * @param {function} method A function implementing the method itself.
- * It will also create a quiet version that will not emit events, to not
- * mess the user code with many `changed` event calls. You can call with
- * `methodName + "Quiet"`.
- *
- * The emitted event comes with a object parameter to the listener with the
- * `methodName` as one attribute.
- */
- function jimpEvMethod(methodName, evName, method) {
- var evNameBefore = 'before-' + evName;
- var evNameAfter = evName.replace(/e$/, '') + 'ed';
- Jimp.prototype[methodName] = function () {
- var wrappedCb;
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
- args[_key4] = arguments[_key4];
- }
- var cb = args[method.length - 1];
- var jimpInstance = this;
- if (typeof cb === 'function') {
- wrappedCb = function wrappedCb() {
- for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
- args[_key5] = arguments[_key5];
- }
- var err = args[0],
- data = args[1];
- if (err) {
- jimpInstance.emitError(methodName, err);
- } else {
- jimpInstance.emitMulti(methodName, evNameAfter, (0, _defineProperty2["default"])({}, methodName, data));
- }
- cb.apply(this, args);
- };
- args[args.length - 1] = wrappedCb;
- } else {
- wrappedCb = false;
- }
- this.emitMulti(methodName, evNameBefore);
- var result;
- try {
- result = method.apply(this, args);
- if (!wrappedCb) {
- this.emitMulti(methodName, evNameAfter, (0, _defineProperty2["default"])({}, methodName, result));
- }
- } catch (error) {
- error.methodName = methodName;
- this.emitError(methodName, error);
- }
- return result;
- };
- Jimp.prototype[methodName + 'Quiet'] = method;
- }
- /**
- * Creates a new image that is a clone of this one.
- * @param {function(Error, Jimp)} cb (optional) A callback for when complete
- * @returns the new image
- */
- jimpEvMethod('clone', 'clone', function (cb) {
- var clone = new Jimp(this);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(clone, null, clone);
- }
- return clone;
- });
- /**
- * Simplify jimpEvMethod call for the common `change` evName.
- * @param {string} methodName name of the method
- * @param {function} method to watch changes for
- */
- function jimpEvChange(methodName, method) {
- jimpEvMethod(methodName, 'change', method);
- }
- /**
- * Sets the type of the image (RGB or RGBA) when saving as PNG format (default is RGBA)
- * @param b A Boolean, true to use RGBA or false to use RGB
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- jimpEvChange('background', function (hex, cb) {
- if (typeof hex !== 'number') {
- return _utils.throwError.call(this, 'hex must be a hexadecimal rgba value', cb);
- }
- this._background = hex;
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- });
- /**
- * Scans through a region of the bitmap, calling a function for each pixel.
- * @param {number} x the x coordinate to begin the scan at
- * @param {number} y the y coordinate to begin the scan at
- * @param w the width of the scan region
- * @param h the height of the scan region
- * @param f a function to call on even pixel; the (x, y) position of the pixel
- * and the index of the pixel in the bitmap buffer are passed to the function
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- jimpEvChange('scan', function (x, y, w, h, f, cb) {
- if (typeof x !== 'number' || typeof y !== 'number') {
- return _utils.throwError.call(this, 'x and y must be numbers', cb);
- }
- if (typeof w !== 'number' || typeof h !== 'number') {
- return _utils.throwError.call(this, 'w and h must be numbers', cb);
- }
- if (typeof f !== 'function') {
- return _utils.throwError.call(this, 'f must be a function', cb);
- }
- var result = (0, _utils.scan)(this, x, y, w, h, f);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, result);
- }
- return result;
- });
- if ("BROWSER" === 'BROWSER') {
- // For use in a web browser or web worker
- /* global self */
- var gl;
- if (typeof window !== 'undefined' && (typeof window === "undefined" ? "undefined" : (0, _typeof2["default"])(window)) === 'object') {
- gl = window;
- }
- if (typeof self !== 'undefined' && (typeof self === "undefined" ? "undefined" : (0, _typeof2["default"])(self)) === 'object') {
- gl = self;
- }
- gl.Jimp = Jimp;
- gl.Buffer = Buffer;
- }
- var _default = Jimp;
- exports["default"] = _default;
- }).call(this,require("buffer").Buffer)
- },{"./composite":370,"./constants":371,"./modules/phash":373,"./request":374,"./utils/image-bitmap":375,"./utils/mime":376,"./utils/promisify":377,"@babel/runtime/helpers/assertThisInitialized":3,"@babel/runtime/helpers/classCallCheck":4,"@babel/runtime/helpers/construct":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":8,"@babel/runtime/helpers/inherits":9,"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/interopRequireWildcard":11,"@babel/runtime/helpers/possibleConstructorReturn":16,"@babel/runtime/helpers/slicedToArray":18,"@babel/runtime/helpers/typeof":20,"@jimp/utils":414,"any-base":22,"buffer":47,"core-js/modules/es.array-buffer.slice":172,"core-js/modules/es.array.concat":173,"core-js/modules/es.array.find":177,"core-js/modules/es.array.for-each":178,"core-js/modules/es.array.index-of":180,"core-js/modules/es.array.iterator":182,"core-js/modules/es.array.join":183,"core-js/modules/es.date.to-string":187,"core-js/modules/es.number.constructor":189,"core-js/modules/es.object.assign":190,"core-js/modules/es.object.entries":193,"core-js/modules/es.object.to-string":197,"core-js/modules/es.parse-int":198,"core-js/modules/es.promise":199,"core-js/modules/es.regexp.exec":200,"core-js/modules/es.regexp.to-string":201,"core-js/modules/es.string.match":204,"core-js/modules/es.string.replace":205,"core-js/modules/es.typed-array.copy-within":208,"core-js/modules/es.typed-array.every":209,"core-js/modules/es.typed-array.fill":210,"core-js/modules/es.typed-array.filter":211,"core-js/modules/es.typed-array.find":213,"core-js/modules/es.typed-array.find-index":212,"core-js/modules/es.typed-array.for-each":216,"core-js/modules/es.typed-array.includes":217,"core-js/modules/es.typed-array.index-of":218,"core-js/modules/es.typed-array.iterator":219,"core-js/modules/es.typed-array.join":220,"core-js/modules/es.typed-array.last-index-of":221,"core-js/modules/es.typed-array.map":222,"core-js/modules/es.typed-array.reduce":224,"core-js/modules/es.typed-array.reduce-right":223,"core-js/modules/es.typed-array.reverse":225,"core-js/modules/es.typed-array.set":226,"core-js/modules/es.typed-array.slice":227,"core-js/modules/es.typed-array.some":228,"core-js/modules/es.typed-array.sort":229,"core-js/modules/es.typed-array.subarray":230,"core-js/modules/es.typed-array.to-locale-string":231,"core-js/modules/es.typed-array.to-string":232,"core-js/modules/es.typed-array.uint8-array":233,"core-js/modules/es.typed-array.uint8-clamped-array":234,"core-js/modules/web.dom-collections.for-each":235,"core-js/modules/web.timers":237,"events":239,"fs":46,"mkdirp":262,"path":286,"pixelmatch":288,"tinycolor2":357}],373:[function(require,module,exports){
- "use strict";
- /*
- Copyright (c) 2011 Elliot Shepherd
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- */
- // https://code.google.com/p/ironchef-team21/source/browse/ironchef_team21/src/ImagePHash.java
- /*
- * pHash-like image hash.
- * Author: Elliot Shepherd (elliot@jarofworms.com
- * Based On: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
- */
- function ImagePHash(size, smallerSize) {
- this.size = this.size || size;
- this.smallerSize = this.smallerSize || smallerSize;
- initCoefficients(this.size);
- }
- ImagePHash.prototype.size = 32;
- ImagePHash.prototype.smallerSize = 8;
- ImagePHash.prototype.distance = function (s1, s2) {
- var counter = 0;
- for (var k = 0; k < s1.length; k++) {
- if (s1[k] !== s2[k]) {
- counter++;
- }
- }
- return counter / s1.length;
- }; // Returns a 'binary string' (like. 001010111011100010) which is easy to do a hamming distance on.
- ImagePHash.prototype.getHash = function (img) {
- /* 1. Reduce size.
- * Like Average Hash, pHash starts with a small image.
- * However, the image is larger than 8x8; 32x32 is a good size.
- * This is really done to simplify the DCT computation and not
- * because it is needed to reduce the high frequencies.
- */
- img = img.clone().resize(this.size, this.size);
- /* 2. Reduce color.
- * The image is reduced to a grayscale just to further simplify
- * the number of computations.
- */
- img.grayscale();
- var vals = [];
- for (var x = 0; x < img.bitmap.width; x++) {
- vals[x] = [];
- for (var y = 0; y < img.bitmap.height; y++) {
- vals[x][y] = intToRGBA(img.getPixelColor(x, y)).b;
- }
- }
- /* 3. Compute the DCT.
- * The DCT separates the image into a collection of frequencies
- * and scalars. While JPEG uses an 8x8 DCT, this algorithm uses
- * a 32x32 DCT.
- */
- var dctVals = applyDCT(vals, this.size);
- /* 4. Reduce the DCT.
- * This is the magic step. While the DCT is 32x32, just keep the
- * top-left 8x8. Those represent the lowest frequencies in the
- * picture.
- */
- /* 5. Compute the average value.
- * Like the Average Hash, compute the mean DCT value (using only
- * the 8x8 DCT low-frequency values and excluding the first term
- * since the DC coefficient can be significantly different from
- * the other values and will throw off the average).
- */
- var total = 0;
- for (var _x = 0; _x < this.smallerSize; _x++) {
- for (var _y = 0; _y < this.smallerSize; _y++) {
- total += dctVals[_x][_y];
- }
- }
- var avg = total / (this.smallerSize * this.smallerSize);
- /* 6. Further reduce the DCT.
- * This is the magic step. Set the 64 hash bits to 0 or 1
- * depending on whether each of the 64 DCT values is above or
- * below the average value. The result doesn't tell us the
- * actual low frequencies; it just tells us the very-rough
- * relative scale of the frequencies to the mean. The result
- * will not vary as long as the overall structure of the image
- * remains the same; this can survive gamma and color histogram
- * adjustments without a problem.
- */
- var hash = '';
- for (var _x2 = 0; _x2 < this.smallerSize; _x2++) {
- for (var _y2 = 0; _y2 < this.smallerSize; _y2++) {
- hash += dctVals[_x2][_y2] > avg ? '1' : '0';
- }
- }
- return hash;
- }; // DCT function stolen from http://stackoverflow.com/questions/4240490/problems-with-dct-and-idct-algorithm-in-java
- function intToRGBA(i) {
- var rgba = {};
- rgba.r = Math.floor(i / Math.pow(256, 3));
- rgba.g = Math.floor((i - rgba.r * Math.pow(256, 3)) / Math.pow(256, 2));
- rgba.b = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2)) / Math.pow(256, 1));
- rgba.a = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2) - rgba.b * Math.pow(256, 1)) / Math.pow(256, 0));
- return rgba;
- }
- var c = [];
- function initCoefficients(size) {
- for (var i = 1; i < size; i++) {
- c[i] = 1;
- }
- c[0] = 1 / Math.sqrt(2.0);
- }
- function applyDCT(f, size) {
- var N = size;
- var F = [];
- for (var u = 0; u < N; u++) {
- F[u] = [];
- for (var v = 0; v < N; v++) {
- var sum = 0;
- for (var i = 0; i < N; i++) {
- for (var j = 0; j < N; j++) {
- sum += Math.cos((2 * i + 1) / (2.0 * N) * u * Math.PI) * Math.cos((2 * j + 1) / (2.0 * N) * v * Math.PI) * f[i][j];
- }
- }
- sum *= c[u] * c[v] / 4;
- F[u][v] = sum;
- }
- }
- return F;
- }
- module.exports = ImagePHash;
- },{}],374:[function(require,module,exports){
- (function (process,Buffer){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- require("core-js/modules/es.symbol");
- require("core-js/modules/es.array.filter");
- require("core-js/modules/es.array.for-each");
- require("core-js/modules/es.object.assign");
- require("core-js/modules/es.object.define-properties");
- require("core-js/modules/es.object.define-property");
- require("core-js/modules/es.object.get-own-property-descriptor");
- require("core-js/modules/es.object.get-own-property-descriptors");
- require("core-js/modules/es.object.keys");
- require("core-js/modules/web.dom-collections.for-each");
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
- /* global XMLHttpRequest */
- if (process.browser || "BROWSER" === 'BROWSER' || typeof process.versions.electron !== 'undefined' && process.type === 'renderer' && typeof XMLHttpRequest === 'function') {
- // If we run into a browser or the electron renderer process,
- // use XHR method instead of Request node module.
- module.exports = function (options, cb) {
- var xhr = new XMLHttpRequest();
- xhr.open('GET', options.url, true);
- xhr.responseType = 'arraybuffer';
- xhr.addEventListener('load', function () {
- if (xhr.status < 400) {
- try {
- var data = Buffer.from(this.response);
- cb(null, xhr, data);
- } catch (error) {
- return cb(new Error('Response is not a buffer for url ' + options.url + '. Error: ' + error.message));
- }
- } else {
- cb(new Error('HTTP Status ' + xhr.status + ' for url ' + options.url));
- }
- });
- xhr.addEventListener('error', function (e) {
- cb(e);
- });
- xhr.send();
- };
- } else {
- module.exports = function (_ref, cb) {
- var options = Object.assign({}, _ref);
- var p = require('phin');
- p(_objectSpread({
- compression: true
- }, options), function (err, res) {
- if (err === null) {
- cb(null, res, res.body);
- } else {
- cb(err);
- }
- });
- };
- }
- }).call(this,require('_process'),require("buffer").Buffer)
- },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"_process":312,"buffer":47,"core-js/modules/es.array.filter":175,"core-js/modules/es.array.for-each":178,"core-js/modules/es.object.assign":190,"core-js/modules/es.object.define-properties":191,"core-js/modules/es.object.define-property":192,"core-js/modules/es.object.get-own-property-descriptor":194,"core-js/modules/es.object.get-own-property-descriptors":195,"core-js/modules/es.object.keys":196,"core-js/modules/es.symbol":207,"core-js/modules/web.dom-collections.for-each":235,"phin":287}],375:[function(require,module,exports){
- (function (Buffer){
- "use strict";
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.parseBitmap = parseBitmap;
- exports.getBuffer = getBuffer;
- exports.getBufferAsync = getBufferAsync;
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
- var _fileType = _interopRequireDefault(require("file-type"));
- var _exifParser = _interopRequireDefault(require("exif-parser"));
- var _utils = require("@jimp/utils");
- var constants = _interopRequireWildcard(require("../constants"));
- var MIME = _interopRequireWildcard(require("./mime"));
- var _promisify = _interopRequireDefault(require("./promisify"));
- function getMIMEFromBuffer(buffer, path) {
- var fileTypeFromBuffer = (0, _fileType["default"])(buffer);
- if (fileTypeFromBuffer) {
- // If fileType returns something for buffer, then return the mime given
- return fileTypeFromBuffer.mime;
- }
- if (path) {
- // If a path is supplied, and fileType yields no results, then retry with MIME
- // Path can be either a file path or a url
- return MIME.getType(path);
- }
- return null;
- }
- /*
- * Obtains image orientation from EXIF metadata.
- *
- * @param img {Jimp} a Jimp image object
- * @returns {number} a number 1-8 representing EXIF orientation,
- * in particular 1 if orientation tag is missing
- */
- function getExifOrientation(img) {
- return img._exif && img._exif.tags && img._exif.tags.Orientation || 1;
- }
- /**
- * Returns a function which translates EXIF-rotated coordinates into
- * non-rotated ones.
- *
- * Transformation reference: http://sylvana.net/jpegcrop/exif_orientation.html.
- *
- * @param img {Jimp} a Jimp image object
- * @returns {function} transformation function for transformBitmap().
- */
- function getExifOrientationTransformation(img) {
- var w = img.getWidth();
- var h = img.getHeight();
- switch (getExifOrientation(img)) {
- case 1:
- // Horizontal (normal)
- // does not need to be supported here
- return null;
- case 2:
- // Mirror horizontal
- return function (x, y) {
- return [w - x - 1, y];
- };
- case 3:
- // Rotate 180
- return function (x, y) {
- return [w - x - 1, h - y - 1];
- };
- case 4:
- // Mirror vertical
- return function (x, y) {
- return [x, h - y - 1];
- };
- case 5:
- // Mirror horizontal and rotate 270 CW
- return function (x, y) {
- return [y, x];
- };
- case 6:
- // Rotate 90 CW
- return function (x, y) {
- return [y, h - x - 1];
- };
- case 7:
- // Mirror horizontal and rotate 90 CW
- return function (x, y) {
- return [w - y - 1, h - x - 1];
- };
- case 8:
- // Rotate 270 CW
- return function (x, y) {
- return [w - y - 1, x];
- };
- default:
- return null;
- }
- }
- /*
- * Transforms bitmap in place (moves pixels around) according to given
- * transformation function.
- *
- * @param img {Jimp} a Jimp image object, which bitmap is supposed to
- * be transformed
- * @param width {number} bitmap width after the transformation
- * @param height {number} bitmap height after the transformation
- * @param transformation {function} transformation function which defines pixel
- * mapping between new and source bitmap. It takes a pair of coordinates
- * in the target, and returns a respective pair of coordinates in
- * the source bitmap, i.e. has following form:
- * `function(new_x, new_y) { return [src_x, src_y] }`.
- */
- function transformBitmap(img, width, height, transformation) {
- // Underscore-prefixed values are related to the source bitmap
- // Their counterparts with no prefix are related to the target bitmap
- var _data = img.bitmap.data;
- var _width = img.bitmap.width;
- var data = Buffer.alloc(_data.length);
- for (var x = 0; x < width; x++) {
- for (var y = 0; y < height; y++) {
- var _transformation = transformation(x, y),
- _transformation2 = (0, _slicedToArray2["default"])(_transformation, 2),
- _x = _transformation2[0],
- _y = _transformation2[1];
- var idx = width * y + x << 2;
- var _idx = _width * _y + _x << 2;
- var pixel = _data.readUInt32BE(_idx);
- data.writeUInt32BE(pixel, idx);
- }
- }
- img.bitmap.data = data;
- img.bitmap.width = width;
- img.bitmap.height = height;
- }
- /*
- * Automagically rotates an image based on its EXIF data (if present).
- * @param img {Jimp} a Jimp image object
- */
- function exifRotate(img) {
- if (getExifOrientation(img) < 2) return;
- var transformation = getExifOrientationTransformation(img);
- var swapDimensions = getExifOrientation(img) > 4;
- var newWidth = swapDimensions ? img.bitmap.height : img.bitmap.width;
- var newHeight = swapDimensions ? img.bitmap.width : img.bitmap.height;
- transformBitmap(img, newWidth, newHeight, transformation);
- } // parses a bitmap from the constructor to the JIMP bitmap property
- function parseBitmap(data, path, cb) {
- var mime = getMIMEFromBuffer(data, path);
- if (typeof mime !== 'string') {
- return cb(new Error('Could not find MIME for Buffer <' + path + '>'));
- }
- this._originalMime = mime.toLowerCase();
- try {
- var _mime = this.getMIME();
- if (this.constructor.decoders[_mime]) {
- this.bitmap = this.constructor.decoders[_mime](data);
- } else {
- return _utils.throwError.call(this, 'Unsupported MIME type: ' + _mime, cb);
- }
- } catch (error) {
- return cb.call(this, error, this);
- }
- try {
- this._exif = _exifParser["default"].create(data).parse();
- exifRotate(this); // EXIF data
- } catch (error) {
- /* meh */
- }
- cb.call(this, null, this);
- return this;
- }
- function compositeBitmapOverBackground(Jimp, image) {
- return new Jimp(image.bitmap.width, image.bitmap.height, image._background).composite(image, 0, 0).bitmap;
- }
- /**
- * Converts the image to a buffer
- * @param {string} mime the mime type of the image buffer to be created
- * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument
- * @returns {Jimp} this for chaining of methods
- */
- function getBuffer(mime, cb) {
- if (mime === constants.AUTO) {
- // allow auto MIME detection
- mime = this.getMIME();
- }
- if (typeof mime !== 'string') {
- return _utils.throwError.call(this, 'mime must be a string', cb);
- }
- if (typeof cb !== 'function') {
- return _utils.throwError.call(this, 'cb must be a function', cb);
- }
- mime = mime.toLowerCase();
- if (this._rgba && this.constructor.hasAlpha[mime]) {
- this.bitmap.data = Buffer.from(this.bitmap.data);
- } else {
- // when format doesn't support alpha
- // composite onto a new image so that the background shows through alpha channels
- this.bitmap.data = compositeBitmapOverBackground(this.constructor, this).data;
- }
- if (this.constructor.encoders[mime]) {
- var buffer = this.constructor.encoders[mime](this);
- cb.call(this, null, buffer);
- } else {
- cb.call(this, 'Unsupported MIME type: ' + mime);
- }
- return this;
- }
- function getBufferAsync(mime) {
- return (0, _promisify["default"])(getBuffer, this, mime);
- }
- }).call(this,require("buffer").Buffer)
- },{"../constants":371,"./mime":376,"./promisify":377,"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/interopRequireWildcard":11,"@babel/runtime/helpers/slicedToArray":18,"@jimp/utils":414,"buffer":47,"exif-parser":240,"file-type":249}],376:[function(require,module,exports){
- "use strict";
- require("core-js/modules/es.array.find");
- require("core-js/modules/es.array.includes");
- require("core-js/modules/es.array.slice");
- require("core-js/modules/es.object.entries");
- require("core-js/modules/es.regexp.exec");
- require("core-js/modules/es.string.includes");
- require("core-js/modules/es.string.split");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getExtension = exports.getType = exports.addType = void 0;
- var mimeTypes = {};
- var findType = function findType(extension) {
- return Object.entries(mimeTypes).find(function (type) {
- return type[1].includes(extension);
- }) || [];
- };
- var addType = function addType(mime, extensions) {
- mimeTypes[mime] = extensions;
- };
- /**
- * Lookup a mime type based on extension
- * @param {string} path path to find extension for
- * @returns {string} mime found mime type
- */
- exports.addType = addType;
- var getType = function getType(path) {
- var pathParts = path.split('/').slice(-1);
- var extension = pathParts[pathParts.length - 1].split('.').pop();
- var type = findType(extension);
- return type[0];
- };
- /**
- * Return file extension associated with a mime type
- * @param {string} type mime type to look up
- * @returns {string} extension file extension
- */
- exports.getType = getType;
- var getExtension = function getExtension(type) {
- return (mimeTypes[type.toLowerCase()] || [])[0];
- };
- exports.getExtension = getExtension;
- },{"core-js/modules/es.array.find":177,"core-js/modules/es.array.includes":179,"core-js/modules/es.array.slice":186,"core-js/modules/es.object.entries":193,"core-js/modules/es.regexp.exec":200,"core-js/modules/es.string.includes":202,"core-js/modules/es.string.split":206}],377:[function(require,module,exports){
- "use strict";
- require("core-js/modules/es.function.bind");
- require("core-js/modules/es.object.to-string");
- require("core-js/modules/es.promise");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var promisify = function promisify(fun, ctx) {
- for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
- args[_key - 2] = arguments[_key];
- }
- return new Promise(function (resolve, reject) {
- args.push(function (err, data) {
- if (err) {
- reject(err);
- }
- resolve(data);
- });
- fun.bind(ctx).apply(void 0, args);
- });
- };
- var _default = promisify;
- exports["default"] = _default;
- module.exports = exports.default;
- },{"core-js/modules/es.function.bind":188,"core-js/modules/es.object.to-string":197,"core-js/modules/es.promise":199}],378:[function(require,module,exports){
- "use strict";
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- require("core-js/modules/es.symbol");
- require("core-js/modules/es.array.filter");
- require("core-js/modules/es.array.for-each");
- require("core-js/modules/es.array.is-array");
- require("core-js/modules/es.object.define-properties");
- require("core-js/modules/es.object.define-property");
- require("core-js/modules/es.object.entries");
- require("core-js/modules/es.object.get-own-property-descriptor");
- require("core-js/modules/es.object.get-own-property-descriptors");
- require("core-js/modules/es.object.keys");
- require("core-js/modules/web.dom-collections.for-each");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = configure;
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
- var _core = _interopRequireWildcard(require("@jimp/core"));
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
- function configure(configuration) {
- var jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _core["default"];
- var jimpConfig = {
- hasAlpha: {},
- encoders: {},
- decoders: {},
- "class": {},
- constants: {}
- };
- function addToConfig(newConfig) {
- Object.entries(newConfig).forEach(function (_ref) {
- var _ref2 = (0, _slicedToArray2["default"])(_ref, 2),
- key = _ref2[0],
- value = _ref2[1];
- jimpConfig[key] = _objectSpread({}, jimpConfig[key], {}, value);
- });
- }
- function addImageType(typeModule) {
- var type = typeModule();
- if (Array.isArray(type.mime)) {
- _core.addType.apply(void 0, (0, _toConsumableArray2["default"])(type.mime));
- } else {
- Object.entries(type.mime).forEach(function (mimeType) {
- return _core.addType.apply(void 0, (0, _toConsumableArray2["default"])(mimeType));
- });
- }
- delete type.mime;
- addToConfig(type);
- }
- function addPlugin(pluginModule) {
- var plugin = pluginModule(_core.jimpEvChange) || {};
- if (!plugin["class"] && !plugin.constants) {
- // Default to class function
- addToConfig({
- "class": plugin
- });
- } else {
- addToConfig(plugin);
- }
- }
- if (configuration.types) {
- configuration.types.forEach(addImageType);
- jimpInstance.decoders = _objectSpread({}, jimpInstance.decoders, {}, jimpConfig.decoders);
- jimpInstance.encoders = _objectSpread({}, jimpInstance.encoders, {}, jimpConfig.encoders);
- jimpInstance.hasAlpha = _objectSpread({}, jimpInstance.hasAlpha, {}, jimpConfig.hasAlpha);
- }
- if (configuration.plugins) {
- configuration.plugins.forEach(addPlugin);
- }
- (0, _core.addJimpMethods)(jimpConfig["class"], jimpInstance);
- (0, _core.addConstants)(jimpConfig.constants, jimpInstance);
- return _core["default"];
- }
- module.exports = exports.default;
- },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/interopRequireWildcard":11,"@babel/runtime/helpers/slicedToArray":18,"@babel/runtime/helpers/toConsumableArray":19,"@jimp/core":372,"core-js/modules/es.array.filter":175,"core-js/modules/es.array.for-each":178,"core-js/modules/es.array.is-array":181,"core-js/modules/es.object.define-properties":191,"core-js/modules/es.object.define-property":192,"core-js/modules/es.object.entries":193,"core-js/modules/es.object.get-own-property-descriptor":194,"core-js/modules/es.object.get-own-property-descriptors":195,"core-js/modules/es.object.keys":196,"core-js/modules/es.symbol":207,"core-js/modules/web.dom-collections.for-each":235}],379:[function(require,module,exports){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _custom = _interopRequireDefault(require("@jimp/custom"));
- var _types = _interopRequireDefault(require("@jimp/types"));
- var _plugins = _interopRequireDefault(require("@jimp/plugins"));
- var _default = (0, _custom["default"])({
- types: [_types["default"]],
- plugins: [_plugins["default"]]
- });
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/custom":378,"@jimp/plugins":407,"@jimp/types":413}],380:[function(require,module,exports){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
- var _utils = require("@jimp/utils");
- var _default = function _default() {
- return {
- /**
- * Blits a source image on to this image
- * @param {Jimp} src the source Jimp instance
- * @param {number} x the x position to blit the image
- * @param {number} y the y position to blit the image
- * @param {number} srcx (optional) the x position from which to crop the source image
- * @param {number} srcy (optional) the y position from which to crop the source image
- * @param {number} srcw (optional) the width to which to crop the source image
- * @param {number} srch (optional) the height to which to crop the source image
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- blit: function blit(src, x, y, srcx, srcy, srcw, srch, cb) {
- if (!(src instanceof this.constructor)) {
- return _utils.throwError.call(this, 'The source must be a Jimp image', cb);
- }
- if (typeof x !== 'number' || typeof y !== 'number') {
- return _utils.throwError.call(this, 'x and y must be numbers', cb);
- }
- if (typeof srcx === 'function') {
- cb = srcx;
- srcx = 0;
- srcy = 0;
- srcw = src.bitmap.width;
- srch = src.bitmap.height;
- } else if ((0, _typeof2["default"])(srcx) === (0, _typeof2["default"])(srcy) && (0, _typeof2["default"])(srcy) === (0, _typeof2["default"])(srcw) && (0, _typeof2["default"])(srcw) === (0, _typeof2["default"])(srch)) {
- srcx = srcx || 0;
- srcy = srcy || 0;
- srcw = srcw || src.bitmap.width;
- srch = srch || src.bitmap.height;
- } else {
- return _utils.throwError.call(this, 'srcx, srcy, srcw, srch must be numbers', cb);
- } // round input
- x = Math.round(x);
- y = Math.round(y); // round input
- srcx = Math.round(srcx);
- srcy = Math.round(srcy);
- srcw = Math.round(srcw);
- srch = Math.round(srch);
- var maxWidth = this.bitmap.width;
- var maxHeight = this.bitmap.height;
- var baseImage = this;
- src.scanQuiet(srcx, srcy, srcw, srch, function (sx, sy, idx) {
- var xOffset = x + sx - srcx;
- var yOffset = y + sy - srcy;
- if (xOffset >= 0 && yOffset >= 0 && maxWidth - xOffset > 0 && maxHeight - yOffset > 0) {
- var dstIdx = baseImage.getPixelIndex(xOffset, yOffset);
- var _src = {
- r: this.bitmap.data[idx],
- g: this.bitmap.data[idx + 1],
- b: this.bitmap.data[idx + 2],
- a: this.bitmap.data[idx + 3]
- };
- var dst = {
- r: baseImage.bitmap.data[dstIdx],
- g: baseImage.bitmap.data[dstIdx + 1],
- b: baseImage.bitmap.data[dstIdx + 2],
- a: baseImage.bitmap.data[dstIdx + 3]
- };
- baseImage.bitmap.data[dstIdx] = (_src.a * (_src.r - dst.r) - dst.r + 255 >> 8) + dst.r;
- baseImage.bitmap.data[dstIdx + 1] = (_src.a * (_src.g - dst.g) - dst.g + 255 >> 8) + dst.g;
- baseImage.bitmap.data[dstIdx + 2] = (_src.a * (_src.b - dst.b) - dst.b + 255 >> 8) + dst.b;
- baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(dst.a + _src.a);
- }
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/typeof":20,"@jimp/utils":414}],381:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.shgTable = exports.mulTable = void 0;
- var mulTable = [1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107, 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221, 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103, 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119, 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151, 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13, 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75, 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229, 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183, 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37, 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61, 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207, 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178, 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153, 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133, 66, 131, 65, 129, 1];
- exports.mulTable = mulTable;
- var shgTable = [0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18, 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20, 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21, 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20, 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22, 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18, 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22, 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24, 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24, 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22, 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25, 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25, 24, 25, 25, 24, 25, 25, 25, 25, 22, 25, 25, 25, 24, 25, 24, 25, 18];
- exports.shgTable = shgTable;
- },{}],382:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- var _blurTables = require("./blur-tables");
- /*
- Superfast Blur (0.5)
- http://www.quasimondo.com/BoxBlurForCanvas/FastBlur.js
- Copyright (c) 2011 Mario Klingemann
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the "Software"), to deal in the Software without
- restriction, including without limitation the rights to use,
- copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the
- Software is furnished to do so, subject to the following
- conditions:
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- */
- var _default = function _default() {
- return {
- /**
- * A fast blur algorithm that produces similar effect to a Gaussian blur - but MUCH quicker
- * @param {number} r the pixel radius of the blur
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- blur: function blur(r, cb) {
- if (typeof r !== 'number') return _utils.throwError.call(this, 'r must be a number', cb);
- if (r < 1) return _utils.throwError.call(this, 'r must be greater than 0', cb);
- var rsum;
- var gsum;
- var bsum;
- var asum;
- var x;
- var y;
- var i;
- var p;
- var p1;
- var p2;
- var yp;
- var yi;
- var yw;
- var pa;
- var wm = this.bitmap.width - 1;
- var hm = this.bitmap.height - 1; // const wh = this.bitmap.width * this.bitmap.height;
- var rad1 = r + 1;
- var mulSum = _blurTables.mulTable[r];
- var shgSum = _blurTables.shgTable[r];
- var red = [];
- var green = [];
- var blue = [];
- var alpha = [];
- var vmin = [];
- var vmax = [];
- var iterations = 2;
- while (iterations-- > 0) {
- yi = 0;
- yw = 0;
- for (y = 0; y < this.bitmap.height; y++) {
- rsum = this.bitmap.data[yw] * rad1;
- gsum = this.bitmap.data[yw + 1] * rad1;
- bsum = this.bitmap.data[yw + 2] * rad1;
- asum = this.bitmap.data[yw + 3] * rad1;
- for (i = 1; i <= r; i++) {
- p = yw + ((i > wm ? wm : i) << 2);
- rsum += this.bitmap.data[p++];
- gsum += this.bitmap.data[p++];
- bsum += this.bitmap.data[p++];
- asum += this.bitmap.data[p];
- }
- for (x = 0; x < this.bitmap.width; x++) {
- red[yi] = rsum;
- green[yi] = gsum;
- blue[yi] = bsum;
- alpha[yi] = asum;
- if (y === 0) {
- vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2;
- vmax[x] = (p = x - r) > 0 ? p << 2 : 0;
- }
- p1 = yw + vmin[x];
- p2 = yw + vmax[x];
- rsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];
- gsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];
- bsum += this.bitmap.data[p1++] - this.bitmap.data[p2++];
- asum += this.bitmap.data[p1] - this.bitmap.data[p2];
- yi++;
- }
- yw += this.bitmap.width << 2;
- }
- for (x = 0; x < this.bitmap.width; x++) {
- yp = x;
- rsum = red[yp] * rad1;
- gsum = green[yp] * rad1;
- bsum = blue[yp] * rad1;
- asum = alpha[yp] * rad1;
- for (i = 1; i <= r; i++) {
- yp += i > hm ? 0 : this.bitmap.width;
- rsum += red[yp];
- gsum += green[yp];
- bsum += blue[yp];
- asum += alpha[yp];
- }
- yi = x << 2;
- for (y = 0; y < this.bitmap.height; y++) {
- pa = asum * mulSum >>> shgSum;
- this.bitmap.data[yi + 3] = pa; // normalize alpha
- if (pa > 255) {
- this.bitmap.data[yi + 3] = 255;
- }
- if (pa > 0) {
- pa = 255 / pa;
- this.bitmap.data[yi] = (rsum * mulSum >>> shgSum) * pa;
- this.bitmap.data[yi + 1] = (gsum * mulSum >>> shgSum) * pa;
- this.bitmap.data[yi + 2] = (bsum * mulSum >>> shgSum) * pa;
- } else {
- this.bitmap.data[yi + 2] = 0;
- this.bitmap.data[yi + 1] = 0;
- this.bitmap.data[yi] = 0;
- }
- if (x === 0) {
- vmin[y] = ((p = y + rad1) < hm ? p : hm) * this.bitmap.width;
- vmax[y] = (p = y - r) > 0 ? p * this.bitmap.width : 0;
- }
- p1 = x + vmin[y];
- p2 = x + vmax[y];
- rsum += red[p1] - red[p2];
- gsum += green[p1] - green[p2];
- bsum += blue[p1] - blue[p2];
- asum += alpha[p1] - alpha[p2];
- yi += this.bitmap.width << 2;
- }
- }
- }
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"./blur-tables":381,"@jimp/utils":414}],383:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Creates a circle out of an image.
- * @param {function(Error, Jimp)} options (optional) radius, x, y
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- var _default = function _default() {
- return {
- circle: function circle() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var cb = arguments.length > 1 ? arguments[1] : undefined;
- if (typeof options === 'function') {
- cb = options;
- options = {};
- }
- var radius = options.radius || (this.bitmap.width > this.bitmap.height ? this.bitmap.height : this.bitmap.width) / 2;
- var center = {
- x: typeof options.x === 'number' ? options.x : this.bitmap.width / 2,
- y: typeof options.y === 'number' ? options.y : this.bitmap.height / 2
- };
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- var curR = Math.sqrt(Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2));
- if (radius - curR <= 0.0) {
- this.bitmap.data[idx + 3] = 0;
- } else if (radius - curR < 1.0) {
- this.bitmap.data[idx + 3] = 255 * (radius - curR);
- }
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414}],384:[function(require,module,exports){
- (function (Buffer){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- require("core-js/modules/es.array.for-each");
- require("core-js/modules/es.array.is-array");
- require("core-js/modules/es.array.map");
- require("core-js/modules/es.parse-int");
- require("core-js/modules/web.dom-collections.for-each");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
- var _tinycolor = _interopRequireDefault(require("tinycolor2"));
- var _utils = require("@jimp/utils");
- function applyKernel(im, kernel, x, y) {
- var value = [0, 0, 0];
- var size = (kernel.length - 1) / 2;
- for (var kx = 0; kx < kernel.length; kx += 1) {
- for (var ky = 0; ky < kernel[kx].length; ky += 1) {
- var idx = im.getPixelIndex(x + kx - size, y + ky - size);
- value[0] += im.bitmap.data[idx] * kernel[kx][ky];
- value[1] += im.bitmap.data[idx + 1] * kernel[kx][ky];
- value[2] += im.bitmap.data[idx + 2] * kernel[kx][ky];
- }
- }
- return value;
- }
- var isDef = function isDef(v) {
- return typeof v !== 'undefined' && v !== null;
- };
- function greyscale(cb) {
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- var grey = parseInt(0.2126 * this.bitmap.data[idx] + 0.7152 * this.bitmap.data[idx + 1] + 0.0722 * this.bitmap.data[idx + 2], 10);
- this.bitmap.data[idx] = grey;
- this.bitmap.data[idx + 1] = grey;
- this.bitmap.data[idx + 2] = grey;
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- function mix(clr, clr2) {
- var p = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50;
- return {
- r: (clr2.r - clr.r) * (p / 100) + clr.r,
- g: (clr2.g - clr.g) * (p / 100) + clr.g,
- b: (clr2.b - clr.b) * (p / 100) + clr.b
- };
- }
- function colorFn(actions, cb) {
- var _this = this;
- if (!actions || !Array.isArray(actions)) {
- return _utils.throwError.call(this, 'actions must be an array', cb);
- }
- actions = actions.map(function (action) {
- if (action.apply === 'xor' || action.apply === 'mix') {
- action.params[0] = (0, _tinycolor["default"])(action.params[0]).toRgb();
- }
- return action;
- });
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- var clr = {
- r: _this.bitmap.data[idx],
- g: _this.bitmap.data[idx + 1],
- b: _this.bitmap.data[idx + 2]
- };
- var colorModifier = function colorModifier(i, amount) {
- return _this.constructor.limit255(clr[i] + amount);
- };
- actions.forEach(function (action) {
- if (action.apply === 'mix') {
- clr = mix(clr, action.params[0], action.params[1]);
- } else if (action.apply === 'tint') {
- clr = mix(clr, {
- r: 255,
- g: 255,
- b: 255
- }, action.params[0]);
- } else if (action.apply === 'shade') {
- clr = mix(clr, {
- r: 0,
- g: 0,
- b: 0
- }, action.params[0]);
- } else if (action.apply === 'xor') {
- clr = {
- r: clr.r ^ action.params[0].r,
- g: clr.g ^ action.params[0].g,
- b: clr.b ^ action.params[0].b
- };
- } else if (action.apply === 'red') {
- clr.r = colorModifier('r', action.params[0]);
- } else if (action.apply === 'green') {
- clr.g = colorModifier('g', action.params[0]);
- } else if (action.apply === 'blue') {
- clr.b = colorModifier('b', action.params[0]);
- } else {
- var _clr;
- if (action.apply === 'hue') {
- action.apply = 'spin';
- }
- clr = (0, _tinycolor["default"])(clr);
- if (!clr[action.apply]) {
- return _utils.throwError.call(_this, 'action ' + action.apply + ' not supported', cb);
- }
- clr = (_clr = clr)[action.apply].apply(_clr, (0, _toConsumableArray2["default"])(action.params)).toRgb();
- }
- });
- _this.bitmap.data[idx] = clr.r;
- _this.bitmap.data[idx + 1] = clr.g;
- _this.bitmap.data[idx + 2] = clr.b;
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- var _default = function _default() {
- return {
- /**
- * Adjusts the brightness of the image
- * @param {number} val the amount to adjust the brightness, a number between -1 and +1
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- brightness: function brightness(val, cb) {
- if (typeof val !== 'number') {
- return _utils.throwError.call(this, 'val must be numbers', cb);
- }
- if (val < -1 || val > +1) {
- return _utils.throwError.call(this, 'val must be a number between -1 and +1', cb);
- }
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- if (val < 0.0) {
- this.bitmap.data[idx] = this.bitmap.data[idx] * (1 + val);
- this.bitmap.data[idx + 1] = this.bitmap.data[idx + 1] * (1 + val);
- this.bitmap.data[idx + 2] = this.bitmap.data[idx + 2] * (1 + val);
- } else {
- this.bitmap.data[idx] = this.bitmap.data[idx] + (255 - this.bitmap.data[idx]) * val;
- this.bitmap.data[idx + 1] = this.bitmap.data[idx + 1] + (255 - this.bitmap.data[idx + 1]) * val;
- this.bitmap.data[idx + 2] = this.bitmap.data[idx + 2] + (255 - this.bitmap.data[idx + 2]) * val;
- }
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Adjusts the contrast of the image
- * @param {number} val the amount to adjust the contrast, a number between -1 and +1
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- contrast: function contrast(val, cb) {
- if (typeof val !== 'number') {
- return _utils.throwError.call(this, 'val must be numbers', cb);
- }
- if (val < -1 || val > +1) {
- return _utils.throwError.call(this, 'val must be a number between -1 and +1', cb);
- }
- var factor = (val + 1) / (1 - val);
- function adjust(value) {
- value = Math.floor(factor * (value - 127) + 127);
- return value < 0 ? 0 : value > 255 ? 255 : value;
- }
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- this.bitmap.data[idx] = adjust(this.bitmap.data[idx]);
- this.bitmap.data[idx + 1] = adjust(this.bitmap.data[idx + 1]);
- this.bitmap.data[idx + 2] = adjust(this.bitmap.data[idx + 2]);
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Apply a posterize effect
- * @param {number} n the amount to adjust the contrast, minimum threshold is two
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- posterize: function posterize(n, cb) {
- if (typeof n !== 'number') {
- return _utils.throwError.call(this, 'n must be numbers', cb);
- }
- if (n < 2) {
- n = 2;
- } // minimum of 2 levels
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- this.bitmap.data[idx] = Math.floor(this.bitmap.data[idx] / 255 * (n - 1)) / (n - 1) * 255;
- this.bitmap.data[idx + 1] = Math.floor(this.bitmap.data[idx + 1] / 255 * (n - 1)) / (n - 1) * 255;
- this.bitmap.data[idx + 2] = Math.floor(this.bitmap.data[idx + 2] / 255 * (n - 1)) / (n - 1) * 255;
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Removes colour from the image using ITU Rec 709 luminance values
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- greyscale: greyscale,
- // Alias of greyscale for our American friends
- grayscale: greyscale,
- /**
- * Multiplies the opacity of each pixel by a factor between 0 and 1
- * @param {number} f A number, the factor by which to multiply the opacity of each pixel
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- opacity: function opacity(f, cb) {
- if (typeof f !== 'number') return _utils.throwError.call(this, 'f must be a number', cb);
- if (f < 0 || f > 1) return _utils.throwError.call(this, 'f must be a number from 0 to 1', cb);
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- var v = this.bitmap.data[idx + 3] * f;
- this.bitmap.data[idx + 3] = v;
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Applies a sepia tone to the image
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- sepia: function sepia(cb) {
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- var red = this.bitmap.data[idx];
- var green = this.bitmap.data[idx + 1];
- var blue = this.bitmap.data[idx + 2];
- red = red * 0.393 + green * 0.769 + blue * 0.189;
- green = red * 0.349 + green * 0.686 + blue * 0.168;
- blue = red * 0.272 + green * 0.534 + blue * 0.131;
- this.bitmap.data[idx] = red < 255 ? red : 255;
- this.bitmap.data[idx + 1] = green < 255 ? green : 255;
- this.bitmap.data[idx + 2] = blue < 255 ? blue : 255;
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Fades each pixel by a factor between 0 and 1
- * @param {number} f A number from 0 to 1. 0 will haven no effect. 1 will turn the image completely transparent.
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- fade: function fade(f, cb) {
- if (typeof f !== 'number') {
- return _utils.throwError.call(this, 'f must be a number', cb);
- }
- if (f < 0 || f > 1) {
- return _utils.throwError.call(this, 'f must be a number from 0 to 1', cb);
- } // this method is an alternative to opacity (which may be deprecated)
- this.opacity(1 - f);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Adds each element of the image to its local neighbors, weighted by the kernel
- * @param {array} kernel a matrix to weight the neighbors sum
- * @param {string} edgeHandling (optional) define how to sum pixels from outside the border
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- convolution: function convolution(kernel, edgeHandling, cb) {
- if (typeof edgeHandling === 'function' && typeof cb === 'undefined') {
- cb = edgeHandling;
- edgeHandling = null;
- }
- if (!edgeHandling) {
- edgeHandling = this.constructor.EDGE_EXTEND;
- }
- var newData = Buffer.from(this.bitmap.data);
- var kRows = kernel.length;
- var kCols = kernel[0].length;
- var rowEnd = Math.floor(kRows / 2);
- var colEnd = Math.floor(kCols / 2);
- var rowIni = -rowEnd;
- var colIni = -colEnd;
- var weight;
- var rSum;
- var gSum;
- var bSum;
- var ri;
- var gi;
- var bi;
- var xi;
- var yi;
- var idxi;
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- bSum = 0;
- gSum = 0;
- rSum = 0;
- for (var row = rowIni; row <= rowEnd; row++) {
- for (var col = colIni; col <= colEnd; col++) {
- xi = x + col;
- yi = y + row;
- weight = kernel[row + rowEnd][col + colEnd];
- idxi = this.getPixelIndex(xi, yi, edgeHandling);
- if (idxi === -1) {
- bi = 0;
- gi = 0;
- ri = 0;
- } else {
- ri = this.bitmap.data[idxi + 0];
- gi = this.bitmap.data[idxi + 1];
- bi = this.bitmap.data[idxi + 2];
- }
- rSum += weight * ri;
- gSum += weight * gi;
- bSum += weight * bi;
- }
- }
- if (rSum < 0) {
- rSum = 0;
- }
- if (gSum < 0) {
- gSum = 0;
- }
- if (bSum < 0) {
- bSum = 0;
- }
- if (rSum > 255) {
- rSum = 255;
- }
- if (gSum > 255) {
- gSum = 255;
- }
- if (bSum > 255) {
- bSum = 255;
- }
- newData[idx + 0] = rSum;
- newData[idx + 1] = gSum;
- newData[idx + 2] = bSum;
- });
- this.bitmap.data = newData;
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Set the alpha channel on every pixel to fully opaque
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- opaque: function opaque(cb) {
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- this.bitmap.data[idx + 3] = 255;
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Pixelates the image or a region
- * @param {number} size the size of the pixels
- * @param {number} x (optional) the x position of the region to pixelate
- * @param {number} y (optional) the y position of the region to pixelate
- * @param {number} w (optional) the width of the region to pixelate
- * @param {number} h (optional) the height of the region to pixelate
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- pixelate: function pixelate(size, x, y, w, h, cb) {
- if (typeof x === 'function') {
- cb = x;
- h = null;
- w = null;
- y = null;
- x = null;
- } else {
- if (typeof size !== 'number') {
- return _utils.throwError.call(this, 'size must be a number', cb);
- }
- if (isDef(x) && typeof x !== 'number') {
- return _utils.throwError.call(this, 'x must be a number', cb);
- }
- if (isDef(y) && typeof y !== 'number') {
- return _utils.throwError.call(this, 'y must be a number', cb);
- }
- if (isDef(w) && typeof w !== 'number') {
- return _utils.throwError.call(this, 'w must be a number', cb);
- }
- if (isDef(h) && typeof h !== 'number') {
- return _utils.throwError.call(this, 'h must be a number', cb);
- }
- }
- var kernel = [[1 / 16, 2 / 16, 1 / 16], [2 / 16, 4 / 16, 2 / 16], [1 / 16, 2 / 16, 1 / 16]];
- x = x || 0;
- y = y || 0;
- w = isDef(w) ? w : this.bitmap.width - x;
- h = isDef(h) ? h : this.bitmap.height - y;
- var source = this.cloneQuiet();
- this.scanQuiet(x, y, w, h, function (xx, yx, idx) {
- xx = size * Math.floor(xx / size);
- yx = size * Math.floor(yx / size);
- var value = applyKernel(source, kernel, xx, yx);
- this.bitmap.data[idx] = value[0];
- this.bitmap.data[idx + 1] = value[1];
- this.bitmap.data[idx + 2] = value[2];
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Applies a convolution kernel to the image or a region
- * @param {array} kernel the convolution kernel
- * @param {number} x (optional) the x position of the region to apply convolution to
- * @param {number} y (optional) the y position of the region to apply convolution to
- * @param {number} w (optional) the width of the region to apply convolution to
- * @param {number} h (optional) the height of the region to apply convolution to
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- convolute: function convolute(kernel, x, y, w, h, cb) {
- if (!Array.isArray(kernel)) return _utils.throwError.call(this, 'the kernel must be an array', cb);
- if (typeof x === 'function') {
- cb = x;
- x = null;
- y = null;
- w = null;
- h = null;
- } else {
- if (isDef(x) && typeof x !== 'number') {
- return _utils.throwError.call(this, 'x must be a number', cb);
- }
- if (isDef(y) && typeof y !== 'number') {
- return _utils.throwError.call(this, 'y must be a number', cb);
- }
- if (isDef(w) && typeof w !== 'number') {
- return _utils.throwError.call(this, 'w must be a number', cb);
- }
- if (isDef(h) && typeof h !== 'number') {
- return _utils.throwError.call(this, 'h must be a number', cb);
- }
- }
- var ksize = (kernel.length - 1) / 2;
- x = isDef(x) ? x : ksize;
- y = isDef(y) ? y : ksize;
- w = isDef(w) ? w : this.bitmap.width - x;
- h = isDef(h) ? h : this.bitmap.height - y;
- var source = this.cloneQuiet();
- this.scanQuiet(x, y, w, h, function (xx, yx, idx) {
- var value = applyKernel(source, kernel, xx, yx);
- this.bitmap.data[idx] = this.constructor.limit255(value[0]);
- this.bitmap.data[idx + 1] = this.constructor.limit255(value[1]);
- this.bitmap.data[idx + 2] = this.constructor.limit255(value[2]);
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Apply multiple color modification rules
- * @param {array} actions list of color modification rules, in following format: { apply: '<rule-name>', params: [ <rule-parameters> ] }
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp }this for chaining of methods
- */
- color: colorFn,
- colour: colorFn
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- }).call(this,require("buffer").Buffer)
- },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/toConsumableArray":19,"@jimp/utils":414,"buffer":47,"core-js/modules/es.array.for-each":178,"core-js/modules/es.array.is-array":181,"core-js/modules/es.array.map":184,"core-js/modules/es.parse-int":198,"core-js/modules/web.dom-collections.for-each":235,"tinycolor2":357}],385:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Scale the image to the given width and height keeping the aspect ratio. Some parts of the image may be letter boxed.
- * @param {number} w the width to resize the image to
- * @param {number} h the height to resize the image to
- * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment
- * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- var _default = function _default() {
- return {
- contain: function contain(w, h, alignBits, mode, cb) {
- if (typeof w !== 'number' || typeof h !== 'number') {
- return _utils.throwError.call(this, 'w and h must be numbers', cb);
- } // permit any sort of optional parameters combination
- if (typeof alignBits === 'string') {
- if (typeof mode === 'function' && typeof cb === 'undefined') cb = mode;
- mode = alignBits;
- alignBits = null;
- }
- if (typeof alignBits === 'function') {
- if (typeof cb === 'undefined') cb = alignBits;
- mode = null;
- alignBits = null;
- }
- if (typeof mode === 'function' && typeof cb === 'undefined') {
- cb = mode;
- mode = null;
- }
- alignBits = alignBits || this.constructor.HORIZONTAL_ALIGN_CENTER | this.constructor.VERTICAL_ALIGN_MIDDLE;
- var hbits = alignBits & (1 << 3) - 1;
- var vbits = alignBits >> 3; // check if more flags than one is in the bit sets
- if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) {
- return _utils.throwError.call(this, 'only use one flag per alignment direction', cb);
- }
- var alignH = hbits >> 1; // 0, 1, 2
- var alignV = vbits >> 1; // 0, 1, 2
- var f = w / h > this.bitmap.width / this.bitmap.height ? h / this.bitmap.height : w / this.bitmap.width;
- var c = this.cloneQuiet().scale(f, mode);
- this.resize(w, h, mode);
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- this.bitmap.data.writeUInt32BE(this._background, idx);
- });
- this.blit(c, (this.bitmap.width - c.bitmap.width) / 2 * alignH, (this.bitmap.height - c.bitmap.height) / 2 * alignV);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414}],386:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Scale the image so the given width and height keeping the aspect ratio. Some parts of the image may be clipped.
- * @param {number} w the width to resize the image to
- * @param {number} h the height to resize the image to
- * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment
- * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- var _default = function _default() {
- return {
- cover: function cover(w, h, alignBits, mode, cb) {
- if (typeof w !== 'number' || typeof h !== 'number') {
- return _utils.throwError.call(this, 'w and h must be numbers', cb);
- }
- if (alignBits && typeof alignBits === 'function' && typeof cb === 'undefined') {
- cb = alignBits;
- alignBits = null;
- mode = null;
- } else if (typeof mode === 'function' && typeof cb === 'undefined') {
- cb = mode;
- mode = null;
- }
- alignBits = alignBits || this.constructor.HORIZONTAL_ALIGN_CENTER | this.constructor.VERTICAL_ALIGN_MIDDLE;
- var hbits = alignBits & (1 << 3) - 1;
- var vbits = alignBits >> 3; // check if more flags than one is in the bit sets
- if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) return _utils.throwError.call(this, 'only use one flag per alignment direction', cb);
- var alignH = hbits >> 1; // 0, 1, 2
- var alignV = vbits >> 1; // 0, 1, 2
- var f = w / h > this.bitmap.width / this.bitmap.height ? w / this.bitmap.width : h / this.bitmap.height;
- this.scale(f, mode);
- this.crop((this.bitmap.width - w) / 2 * alignH, (this.bitmap.height - h) / 2 * alignV, w, h);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414}],387:[function(require,module,exports){
- (function (Buffer){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- require("core-js/modules/es.array.slice");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = pluginCrop;
- var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
- var _utils = require("@jimp/utils");
- /* eslint-disable no-labels */
- function pluginCrop(event) {
- /**
- * Crops the image at a given point to a give size
- * @param {number} x the x coordinate to crop form
- * @param {number} y the y coordinate to crop form
- * @param w the width of the crop region
- * @param h the height of the crop region
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- event('crop', function (x, y, w, h, cb) {
- if (typeof x !== 'number' || typeof y !== 'number') return _utils.throwError.call(this, 'x and y must be numbers', cb);
- if (typeof w !== 'number' || typeof h !== 'number') return _utils.throwError.call(this, 'w and h must be numbers', cb); // round input
- x = Math.round(x);
- y = Math.round(y);
- w = Math.round(w);
- h = Math.round(h);
- if (x === 0 && w === this.bitmap.width) {
- // shortcut
- var start = w * y + x << 2;
- var end = start + h * w << 2;
- this.bitmap.data = this.bitmap.data.slice(start, end);
- } else {
- var bitmap = Buffer.allocUnsafe(w * h * 4);
- var offset = 0;
- this.scanQuiet(x, y, w, h, function (x, y, idx) {
- var data = this.bitmap.data.readUInt32BE(idx, true);
- bitmap.writeUInt32BE(data, offset, true);
- offset += 4;
- });
- this.bitmap.data = bitmap;
- }
- this.bitmap.width = w;
- this.bitmap.height = h;
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- });
- return {
- "class": {
- /**
- * Autocrop same color borders from this image
- * @param {number} tolerance (optional): a percent value of tolerance for pixels color difference (default: 0.0002%)
- * @param {boolean} cropOnlyFrames (optional): flag to crop only real frames: all 4 sides of the image must have some border (default: true)
- * @param {function(Error, Jimp)} cb (optional): a callback for when complete (default: no callback)
- * @returns {Jimp} this for chaining of methods
- */
- autocrop: function autocrop() {
- var w = this.bitmap.width;
- var h = this.bitmap.height;
- var minPixelsPerSide = 1; // to avoid cropping completely the image, resulting in an invalid 0 sized image
- var cb; // callback
- var leaveBorder = 0; // Amount of pixels in border to leave
- var tolerance = 0.0002; // percent of color difference tolerance (default value)
- var cropOnlyFrames = true; // flag to force cropping only if the image has a real "frame"
- // i.e. all 4 sides have some border (default value)
- var cropSymmetric = false; // flag to force cropping top be symmetric.
- // i.e. north and south / east and west are cropped by the same value
- // parse arguments
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- for (var a = 0, len = args.length; a < len; a++) {
- if (typeof args[a] === 'number') {
- // tolerance value passed
- tolerance = args[a];
- }
- if (typeof args[a] === 'boolean') {
- // cropOnlyFrames value passed
- cropOnlyFrames = args[a];
- }
- if (typeof args[a] === 'function') {
- // callback value passed
- cb = args[a];
- }
- if ((0, _typeof2["default"])(args[a]) === 'object') {
- // config object passed
- var config = args[a];
- if (typeof config.tolerance !== 'undefined') {
- tolerance = config.tolerance;
- }
- if (typeof config.cropOnlyFrames !== 'undefined') {
- cropOnlyFrames = config.cropOnlyFrames;
- }
- if (typeof config.cropSymmetric !== 'undefined') {
- cropSymmetric = config.cropSymmetric;
- }
- if (typeof config.leaveBorder !== 'undefined') {
- leaveBorder = config.leaveBorder;
- }
- }
- }
- /**
- * All borders must be of the same color as the top left pixel, to be cropped.
- * It should be possible to crop borders each with a different color,
- * but since there are many ways for corners to intersect, it would
- * introduce unnecessary complexity to the algorithm.
- */
- // scan each side for same color borders
- var colorTarget = this.getPixelColor(0, 0); // top left pixel color is the target color
- var rgba1 = this.constructor.intToRGBA(colorTarget); // for north and east sides
- var northPixelsToCrop = 0;
- var eastPixelsToCrop = 0;
- var southPixelsToCrop = 0;
- var westPixelsToCrop = 0; // north side (scan rows from north to south)
- colorTarget = this.getPixelColor(0, 0);
- north: for (var y = 0; y < h - minPixelsPerSide; y++) {
- for (var x = 0; x < w; x++) {
- var colorXY = this.getPixelColor(x, y);
- var rgba2 = this.constructor.intToRGBA(colorXY);
- if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) {
- // this pixel is too distant from the first one: abort this side scan
- break north;
- }
- } // this row contains all pixels with the same color: increment this side pixels to crop
- northPixelsToCrop++;
- } // east side (scan columns from east to west)
- colorTarget = this.getPixelColor(w, 0);
- east: for (var _x = 0; _x < w - minPixelsPerSide; _x++) {
- for (var _y = 0 + northPixelsToCrop; _y < h; _y++) {
- var _colorXY = this.getPixelColor(_x, _y);
- var _rgba = this.constructor.intToRGBA(_colorXY);
- if (this.constructor.colorDiff(rgba1, _rgba) > tolerance) {
- // this pixel is too distant from the first one: abort this side scan
- break east;
- }
- } // this column contains all pixels with the same color: increment this side pixels to crop
- eastPixelsToCrop++;
- } // south side (scan rows from south to north)
- colorTarget = this.getPixelColor(0, h);
- south: for (var _y2 = h - 1; _y2 >= northPixelsToCrop + minPixelsPerSide; _y2--) {
- for (var _x2 = w - eastPixelsToCrop - 1; _x2 >= 0; _x2--) {
- var _colorXY2 = this.getPixelColor(_x2, _y2);
- var _rgba2 = this.constructor.intToRGBA(_colorXY2);
- if (this.constructor.colorDiff(rgba1, _rgba2) > tolerance) {
- // this pixel is too distant from the first one: abort this side scan
- break south;
- }
- } // this row contains all pixels with the same color: increment this side pixels to crop
- southPixelsToCrop++;
- } // west side (scan columns from west to east)
- colorTarget = this.getPixelColor(w, h);
- west: for (var _x3 = w - 1; _x3 >= 0 + eastPixelsToCrop + minPixelsPerSide; _x3--) {
- for (var _y3 = h - 1; _y3 >= 0 + northPixelsToCrop; _y3--) {
- var _colorXY3 = this.getPixelColor(_x3, _y3);
- var _rgba3 = this.constructor.intToRGBA(_colorXY3);
- if (this.constructor.colorDiff(rgba1, _rgba3) > tolerance) {
- // this pixel is too distant from the first one: abort this side scan
- break west;
- }
- } // this column contains all pixels with the same color: increment this side pixels to crop
- westPixelsToCrop++;
- } // decide if a crop is needed
- var doCrop = false; // apply leaveBorder
- westPixelsToCrop -= leaveBorder;
- eastPixelsToCrop -= leaveBorder;
- northPixelsToCrop -= leaveBorder;
- southPixelsToCrop -= leaveBorder;
- if (cropSymmetric) {
- var horizontal = Math.min(eastPixelsToCrop, westPixelsToCrop);
- var vertical = Math.min(northPixelsToCrop, southPixelsToCrop);
- westPixelsToCrop = horizontal;
- eastPixelsToCrop = horizontal;
- northPixelsToCrop = vertical;
- southPixelsToCrop = vertical;
- } // make sure that crops are >= 0
- westPixelsToCrop = westPixelsToCrop >= 0 ? westPixelsToCrop : 0;
- eastPixelsToCrop = eastPixelsToCrop >= 0 ? eastPixelsToCrop : 0;
- northPixelsToCrop = northPixelsToCrop >= 0 ? northPixelsToCrop : 0;
- southPixelsToCrop = southPixelsToCrop >= 0 ? southPixelsToCrop : 0; // safety checks
- var widthOfRemainingPixels = w - (westPixelsToCrop + eastPixelsToCrop);
- var heightOfRemainingPixels = h - (southPixelsToCrop + northPixelsToCrop);
- if (cropOnlyFrames) {
- // crop image if all sides should be cropped
- doCrop = eastPixelsToCrop !== 0 && northPixelsToCrop !== 0 && westPixelsToCrop !== 0 && southPixelsToCrop !== 0;
- } else {
- // crop image if at least one side should be cropped
- doCrop = eastPixelsToCrop !== 0 || northPixelsToCrop !== 0 || westPixelsToCrop !== 0 || southPixelsToCrop !== 0;
- }
- if (doCrop) {
- // do the real crop
- this.crop(eastPixelsToCrop, northPixelsToCrop, widthOfRemainingPixels, heightOfRemainingPixels);
- }
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- }
- };
- }
- module.exports = exports.default;
- }).call(this,require("buffer").Buffer)
- },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/typeof":20,"@jimp/utils":414,"buffer":47,"core-js/modules/es.array.slice":186}],388:[function(require,module,exports){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
- var _utils = require("@jimp/utils");
- /**
- * Displaces the image based on the provided displacement map
- * @param {object} map the source Jimp instance
- * @param {number} offset the maximum displacement value
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- var _default = function _default() {
- return {
- displace: function displace(map, offset, cb) {
- if ((0, _typeof2["default"])(map) !== 'object' || map.constructor !== this.constructor) {
- return _utils.throwError.call(this, 'The source must be a Jimp image', cb);
- }
- if (typeof offset !== 'number') {
- return _utils.throwError.call(this, 'factor must be a number', cb);
- }
- var source = this.cloneQuiet();
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- var displacement = map.bitmap.data[idx] / 256 * offset;
- displacement = Math.round(displacement);
- var ids = this.getPixelIndex(x + displacement, y);
- this.bitmap.data[ids] = source.bitmap.data[idx];
- this.bitmap.data[ids + 1] = source.bitmap.data[idx + 1];
- this.bitmap.data[ids + 2] = source.bitmap.data[idx + 2];
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/typeof":20,"@jimp/utils":414}],389:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Apply a ordered dithering effect
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- function dither(cb) {
- var rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6];
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- var thresholdId = ((y & 3) << 2) + x % 4;
- var dither = rgb565Matrix[thresholdId];
- this.bitmap.data[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff);
- this.bitmap.data[idx + 1] = Math.min(this.bitmap.data[idx + 1] + dither, 0xff);
- this.bitmap.data[idx + 2] = Math.min(this.bitmap.data[idx + 2] + dither, 0xff);
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- var _default = function _default() {
- return {
- dither565: dither,
- dither16: dither
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414}],390:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Creates a circle out of an image.
- * @param {object} options (optional) r: radius of effect
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- var _default = function _default() {
- return {
- fisheye: function fisheye() {
- var _this = this;
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
- r: 2.5
- };
- var cb = arguments.length > 1 ? arguments[1] : undefined;
- if (typeof options === 'function') {
- cb = options;
- options = {
- r: 2.5
- };
- }
- var source = this.cloneQuiet();
- var _source$bitmap = source.bitmap,
- width = _source$bitmap.width,
- height = _source$bitmap.height;
- source.scanQuiet(0, 0, width, height, function (x, y) {
- var hx = x / width;
- var hy = y / height;
- var r = Math.sqrt(Math.pow(hx - 0.5, 2) + Math.pow(hy - 0.5, 2));
- var rn = 2 * Math.pow(r, options.r);
- var cosA = (hx - 0.5) / r;
- var sinA = (hy - 0.5) / r;
- var newX = Math.round((rn * cosA + 0.5) * width);
- var newY = Math.round((rn * sinA + 0.5) * height);
- var color = source.getPixelColor(newX, newY);
- _this.setPixelColor(color, x, y);
- });
- /* Set center pixel color, otherwise it will be transparent */
- this.setPixelColor(source.getPixelColor(width / 2, height / 2), width / 2, height / 2);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414}],391:[function(require,module,exports){
- (function (Buffer){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Flip the image horizontally
- * @param {boolean} horizontal a Boolean, if true the image will be flipped horizontally
- * @param {boolean} vertical a Boolean, if true the image will be flipped vertically
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- function flipFn(horizontal, vertical, cb) {
- if (typeof horizontal !== 'boolean' || typeof vertical !== 'boolean') return _utils.throwError.call(this, 'horizontal and vertical must be Booleans', cb);
- var bitmap = Buffer.alloc(this.bitmap.data.length);
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- var _x = horizontal ? this.bitmap.width - 1 - x : x;
- var _y = vertical ? this.bitmap.height - 1 - y : y;
- var _idx = this.bitmap.width * _y + _x << 2;
- var data = this.bitmap.data.readUInt32BE(idx);
- bitmap.writeUInt32BE(data, _idx);
- });
- this.bitmap.data = Buffer.from(bitmap);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- var _default = function _default() {
- return {
- flip: flipFn,
- mirror: flipFn
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- }).call(this,require("buffer").Buffer)
- },{"@jimp/utils":414,"buffer":47}],392:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Applies a true Gaussian blur to the image (warning: this is VERY slow)
- * @param {number} r the pixel radius of the blur
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- var _default = function _default() {
- return {
- gaussian: function gaussian(r, cb) {
- // http://blog.ivank.net/fastest-gaussian-blur.html
- if (typeof r !== 'number') {
- return _utils.throwError.call(this, 'r must be a number', cb);
- }
- if (r < 1) {
- return _utils.throwError.call(this, 'r must be greater than 0', cb);
- }
- var rs = Math.ceil(r * 2.57); // significant radius
- var range = rs * 2 + 1;
- var rr2 = r * r * 2;
- var rr2pi = rr2 * Math.PI;
- var weights = [];
- for (var y = 0; y < range; y++) {
- weights[y] = [];
- for (var x = 0; x < range; x++) {
- var dsq = Math.pow(x - rs, 2) + Math.pow(y - rs, 2);
- weights[y][x] = Math.exp(-dsq / rr2) / rr2pi;
- }
- }
- for (var _y = 0; _y < this.bitmap.height; _y++) {
- for (var _x = 0; _x < this.bitmap.width; _x++) {
- var red = 0;
- var green = 0;
- var blue = 0;
- var alpha = 0;
- var wsum = 0;
- for (var iy = 0; iy < range; iy++) {
- for (var ix = 0; ix < range; ix++) {
- var x1 = Math.min(this.bitmap.width - 1, Math.max(0, ix + _x - rs));
- var y1 = Math.min(this.bitmap.height - 1, Math.max(0, iy + _y - rs));
- var weight = weights[iy][ix];
- var _idx = y1 * this.bitmap.width + x1 << 2;
- red += this.bitmap.data[_idx] * weight;
- green += this.bitmap.data[_idx + 1] * weight;
- blue += this.bitmap.data[_idx + 2] * weight;
- alpha += this.bitmap.data[_idx + 3] * weight;
- wsum += weight;
- }
- var idx = _y * this.bitmap.width + _x << 2;
- this.bitmap.data[idx] = Math.round(red / wsum);
- this.bitmap.data[idx + 1] = Math.round(green / wsum);
- this.bitmap.data[idx + 2] = Math.round(blue / wsum);
- this.bitmap.data[idx + 3] = Math.round(alpha / wsum);
- }
- }
- }
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414}],393:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Inverts the image
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- var _default = function _default() {
- return {
- invert: function invert(cb) {
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- this.bitmap.data[idx] = 255 - this.bitmap.data[idx];
- this.bitmap.data[idx + 1] = 255 - this.bitmap.data[idx + 1];
- this.bitmap.data[idx + 2] = 255 - this.bitmap.data[idx + 2];
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414}],394:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Masks a source image on to this image using average pixel colour. A completely black pixel on the mask will turn a pixel in the image completely transparent.
- * @param {Jimp} src the source Jimp instance
- * @param {number} x the horizontal position to blit the image
- * @param {number} y the vertical position to blit the image
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- var _default = function _default() {
- return {
- mask: function mask(src) {
- var x = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- var y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
- var cb = arguments.length > 3 ? arguments[3] : undefined;
- if (!(src instanceof this.constructor)) {
- return _utils.throwError.call(this, 'The source must be a Jimp image', cb);
- }
- if (typeof x !== 'number' || typeof y !== 'number') {
- return _utils.throwError.call(this, 'x and y must be numbers', cb);
- } // round input
- x = Math.round(x);
- y = Math.round(y);
- var w = this.bitmap.width;
- var h = this.bitmap.height;
- var baseImage = this;
- src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function (sx, sy, idx) {
- var destX = x + sx;
- var destY = y + sy;
- if (destX >= 0 && destY >= 0 && destX < w && destY < h) {
- var dstIdx = baseImage.getPixelIndex(destX, destY);
- var data = this.bitmap.data;
- var avg = (data[idx + 0] + data[idx + 1] + data[idx + 2]) / 3;
- baseImage.bitmap.data[dstIdx + 3] *= avg / 255;
- }
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414}],395:[function(require,module,exports){
- "use strict";
- require("core-js/modules/es.array.fill");
- require("core-js/modules/es.array.find-index");
- require("core-js/modules/es.array.reverse");
- require("core-js/modules/es.array.slice");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Get an image's histogram
- * @return {object} An object with an array of color occurrence counts for each channel (r,g,b)
- */
- function histogram() {
- var histogram = {
- r: new Array(256).fill(0),
- g: new Array(256).fill(0),
- b: new Array(256).fill(0)
- };
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, index) {
- histogram.r[this.bitmap.data[index + 0]]++;
- histogram.g[this.bitmap.data[index + 1]]++;
- histogram.b[this.bitmap.data[index + 2]]++;
- });
- return histogram;
- }
- /**
- * Normalize values
- * @param {integer} value Pixel channel value.
- * @param {integer} min Minimum value for channel
- * @param {integer} max Maximum value for channel
- * @return {integer} normalized values
- */
- var _normalize = function normalize(value, min, max) {
- return (value - min) * 255 / (max - min);
- };
- var getBounds = function getBounds(histogramChannel) {
- return [histogramChannel.findIndex(function (value) {
- return value > 0;
- }), 255 - histogramChannel.slice().reverse().findIndex(function (value) {
- return value > 0;
- })];
- };
- /**
- * Normalizes the image
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- var _default = function _default() {
- return {
- normalize: function normalize(cb) {
- var h = histogram.call(this); // store bounds (minimum and maximum values)
- var bounds = {
- r: getBounds(h.r),
- g: getBounds(h.g),
- b: getBounds(h.b)
- }; // apply value transformations
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- var r = this.bitmap.data[idx + 0];
- var g = this.bitmap.data[idx + 1];
- var b = this.bitmap.data[idx + 2];
- this.bitmap.data[idx + 0] = _normalize(r, bounds.r[0], bounds.r[1]);
- this.bitmap.data[idx + 1] = _normalize(g, bounds.g[0], bounds.g[1]);
- this.bitmap.data[idx + 2] = _normalize(b, bounds.b[0], bounds.b[1]);
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414,"core-js/modules/es.array.fill":174,"core-js/modules/es.array.find-index":176,"core-js/modules/es.array.reverse":185,"core-js/modules/es.array.slice":186}],396:[function(require,module,exports){
- (function (__dirname){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- require("core-js/modules/es.array.concat");
- require("core-js/modules/es.array.for-each");
- require("core-js/modules/es.array.iterator");
- require("core-js/modules/es.array.join");
- require("core-js/modules/es.array.map");
- require("core-js/modules/es.date.to-string");
- require("core-js/modules/es.object.entries");
- require("core-js/modules/es.object.to-string");
- require("core-js/modules/es.promise");
- require("core-js/modules/es.regexp.exec");
- require("core-js/modules/es.regexp.to-string");
- require("core-js/modules/es.string.iterator");
- require("core-js/modules/es.string.split");
- require("core-js/modules/web.dom-collections.for-each");
- require("core-js/modules/web.dom-collections.iterator");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
- var _path = _interopRequireDefault(require("path"));
- var _loadBmfont = _interopRequireDefault(require("load-bmfont"));
- var _utils = require("@jimp/utils");
- var _measureText = require("./measure-text");
- function xOffsetBasedOnAlignment(constants, font, line, maxWidth, alignment) {
- if (alignment === constants.HORIZONTAL_ALIGN_LEFT) {
- return 0;
- }
- if (alignment === constants.HORIZONTAL_ALIGN_CENTER) {
- return (maxWidth - (0, _measureText.measureText)(font, line)) / 2;
- }
- return maxWidth - (0, _measureText.measureText)(font, line);
- }
- function drawCharacter(image, font, x, y, _char) {
- if (_char.width > 0 && _char.height > 0) {
- var characterPage = font.pages[_char.page];
- image.blit(characterPage, x + _char.xoffset, y + _char.yoffset, _char.x, _char.y, _char.width, _char.height);
- }
- return image;
- }
- function printText(font, x, y, text, defaultCharWidth) {
- for (var i = 0; i < text.length; i++) {
- var _char2 = void 0;
- if (font.chars[text[i]]) {
- _char2 = text[i];
- } else if (/\s/.test(text[i])) {
- _char2 = '';
- } else {
- _char2 = '?';
- }
- var fontChar = font.chars[_char2] || {};
- var fontKerning = font.kernings[_char2];
- drawCharacter(this, font, x, y, fontChar || {});
- var kerning = fontKerning && fontKerning[text[i + 1]] ? fontKerning[text[i + 1]] : 0;
- x += kerning + (fontChar.xadvance || defaultCharWidth);
- }
- }
- function splitLines(font, text, maxWidth) {
- var words = text.split(' ');
- var lines = [];
- var currentLine = [];
- var longestLine = 0;
- words.forEach(function (word) {
- var line = [].concat((0, _toConsumableArray2["default"])(currentLine), [word]).join(' ');
- var length = (0, _measureText.measureText)(font, line);
- if (length <= maxWidth) {
- if (length > longestLine) {
- longestLine = length;
- }
- currentLine.push(word);
- } else {
- lines.push(currentLine);
- currentLine = [word];
- }
- });
- lines.push(currentLine);
- return {
- lines: lines,
- longestLine: longestLine
- };
- }
- function loadPages(Jimp, dir, pages) {
- var newPages = pages.map(function (page) {
- return Jimp.read(dir + '/' + page);
- });
- return Promise.all(newPages);
- }
- var dir = "browser/lib/" || "".concat(__dirname, "/../");
- var _default = function _default() {
- return {
- constants: {
- measureText: _measureText.measureText,
- measureTextHeight: _measureText.measureTextHeight,
- FONT_SANS_8_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt'),
- FONT_SANS_10_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt'),
- FONT_SANS_12_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt'),
- FONT_SANS_14_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt'),
- FONT_SANS_16_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt'),
- FONT_SANS_32_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt'),
- FONT_SANS_64_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt'),
- FONT_SANS_128_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt'),
- FONT_SANS_8_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt'),
- FONT_SANS_16_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt'),
- FONT_SANS_32_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt'),
- FONT_SANS_64_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt'),
- FONT_SANS_128_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt'),
- /**
- * Loads a bitmap font from a file
- * @param {string} file the file path of a .fnt file
- * @param {function(Error, Jimp)} cb (optional) a function to call when the font is loaded
- * @returns {Promise} a promise
- */
- loadFont: function loadFont(file, cb) {
- var _this = this;
- if (typeof file !== 'string') return _utils.throwError.call(this, 'file must be a string', cb);
- return new Promise(function (resolve, reject) {
- cb = cb || function (err, font) {
- if (err) reject(err);else resolve(font);
- };
- (0, _loadBmfont["default"])(file, function (err, font) {
- var chars = {};
- var kernings = {};
- if (err) {
- return _utils.throwError.call(_this, err, cb);
- }
- for (var i = 0; i < font.chars.length; i++) {
- chars[String.fromCharCode(font.chars[i].id)] = font.chars[i];
- }
- for (var _i = 0; _i < font.kernings.length; _i++) {
- var firstString = String.fromCharCode(font.kernings[_i].first);
- kernings[firstString] = kernings[firstString] || {};
- kernings[firstString][String.fromCharCode(font.kernings[_i].second)] = font.kernings[_i].amount;
- }
- loadPages(_this, _path["default"].dirname(file), font.pages).then(function (pages) {
- cb(null, {
- chars: chars,
- kernings: kernings,
- pages: pages,
- common: font.common,
- info: font.info
- });
- });
- });
- });
- }
- },
- "class": {
- /**
- * Draws a text on a image on a given boundary
- * @param {Jimp} font a bitmap font loaded from `Jimp.loadFont` command
- * @param {number} x the x position to start drawing the text
- * @param {number} y the y position to start drawing the text
- * @param {any} text the text to draw (string or object with `text`, `alignmentX`, and/or `alignmentY`)
- * @param {number} maxWidth (optional) the boundary width to draw in
- * @param {number} maxHeight (optional) the boundary height to draw in
- * @param {function(Error, Jimp)} cb (optional) a function to call when the text is written
- * @returns {Jimp} this for chaining of methods
- */
- print: function print(font, x, y, text, maxWidth, maxHeight, cb) {
- var _this2 = this;
- if (typeof maxWidth === 'function' && typeof cb === 'undefined') {
- cb = maxWidth;
- maxWidth = Infinity;
- }
- if (typeof maxWidth === 'undefined') {
- maxWidth = Infinity;
- }
- if (typeof maxHeight === 'function' && typeof cb === 'undefined') {
- cb = maxHeight;
- maxHeight = Infinity;
- }
- if (typeof maxHeight === 'undefined') {
- maxHeight = Infinity;
- }
- if ((0, _typeof2["default"])(font) !== 'object') {
- return _utils.throwError.call(this, 'font must be a Jimp loadFont', cb);
- }
- if (typeof x !== 'number' || typeof y !== 'number' || typeof maxWidth !== 'number') {
- return _utils.throwError.call(this, 'x, y and maxWidth must be numbers', cb);
- }
- if (typeof maxWidth !== 'number') {
- return _utils.throwError.call(this, 'maxWidth must be a number', cb);
- }
- if (typeof maxHeight !== 'number') {
- return _utils.throwError.call(this, 'maxHeight must be a number', cb);
- }
- var alignmentX;
- var alignmentY;
- if ((0, _typeof2["default"])(text) === 'object' && text.text !== null && text.text !== undefined) {
- alignmentX = text.alignmentX || this.constructor.HORIZONTAL_ALIGN_LEFT;
- alignmentY = text.alignmentY || this.constructor.VERTICAL_ALIGN_TOP;
- var _text = text;
- text = _text.text;
- } else {
- alignmentX = this.constructor.HORIZONTAL_ALIGN_LEFT;
- alignmentY = this.constructor.VERTICAL_ALIGN_TOP;
- text = text.toString();
- }
- if (maxHeight !== Infinity && alignmentY === this.constructor.VERTICAL_ALIGN_BOTTOM) {
- y += maxHeight - (0, _measureText.measureTextHeight)(font, text, maxWidth);
- } else if (maxHeight !== Infinity && alignmentY === this.constructor.VERTICAL_ALIGN_MIDDLE) {
- y += maxHeight / 2 - (0, _measureText.measureTextHeight)(font, text, maxWidth) / 2;
- }
- var defaultCharWidth = Object.entries(font.chars)[0][1].xadvance;
- var _splitLines = splitLines(font, text, maxWidth),
- lines = _splitLines.lines,
- longestLine = _splitLines.longestLine;
- lines.forEach(function (line) {
- var lineString = line.join(' ');
- var alignmentWidth = xOffsetBasedOnAlignment(_this2.constructor, font, lineString, maxWidth, alignmentX);
- printText.call(_this2, font, x + alignmentWidth, y, lineString, defaultCharWidth);
- y += font.common.lineHeight;
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this, {
- x: x + longestLine,
- y: y
- });
- }
- return this;
- }
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- }).call(this,"/../../node_modules/@jimp/plugin-print/dist")
- },{"./measure-text":397,"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/toConsumableArray":19,"@babel/runtime/helpers/typeof":20,"@jimp/utils":414,"core-js/modules/es.array.concat":173,"core-js/modules/es.array.for-each":178,"core-js/modules/es.array.iterator":182,"core-js/modules/es.array.join":183,"core-js/modules/es.array.map":184,"core-js/modules/es.date.to-string":187,"core-js/modules/es.object.entries":193,"core-js/modules/es.object.to-string":197,"core-js/modules/es.promise":199,"core-js/modules/es.regexp.exec":200,"core-js/modules/es.regexp.to-string":201,"core-js/modules/es.string.iterator":203,"core-js/modules/es.string.split":206,"core-js/modules/web.dom-collections.for-each":235,"core-js/modules/web.dom-collections.iterator":236,"load-bmfont":398,"path":286}],397:[function(require,module,exports){
- "use strict";
- require("core-js/modules/es.regexp.exec");
- require("core-js/modules/es.string.split");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.measureText = measureText;
- exports.measureTextHeight = measureTextHeight;
- function measureText(font, text) {
- var x = 0;
- for (var i = 0; i < text.length; i++) {
- if (font.chars[text[i]]) {
- var kerning = font.kernings[text[i]] && font.kernings[text[i]][text[i + 1]] ? font.kernings[text[i]][text[i + 1]] : 0;
- x += (font.chars[text[i]].xadvance || 0) + kerning;
- }
- }
- return x;
- }
- function measureTextHeight(font, text, maxWidth) {
- var words = text.split(' ');
- var line = '';
- var textTotalHeight = font.common.lineHeight;
- for (var n = 0; n < words.length; n++) {
- var testLine = line + words[n] + ' ';
- var testWidth = measureText(font, testLine);
- if (testWidth > maxWidth && n > 0) {
- textTotalHeight += font.common.lineHeight;
- line = words[n] + ' ';
- } else {
- line = testLine;
- }
- }
- return textTotalHeight;
- }
- },{"core-js/modules/es.regexp.exec":200,"core-js/modules/es.string.split":206}],398:[function(require,module,exports){
- (function (Buffer){
- var xhr = require('xhr')
- var noop = function(){}
- var parseASCII = require('parse-bmfont-ascii')
- var parseXML = require('parse-bmfont-xml')
- var readBinary = require('parse-bmfont-binary')
- var isBinaryFormat = require('./lib/is-binary')
- var xtend = require('xtend')
- var xml2 = (function hasXML2() {
- return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
- })()
- module.exports = function(opt, cb) {
- cb = typeof cb === 'function' ? cb : noop
- if (typeof opt === 'string')
- opt = { uri: opt }
- else if (!opt)
- opt = {}
- var expectBinary = opt.binary
- if (expectBinary)
- opt = getBinaryOpts(opt)
- xhr(opt, function(err, res, body) {
- if (err)
- return cb(err)
- if (!/^2/.test(res.statusCode))
- return cb(new Error('http status code: '+res.statusCode))
- if (!body)
- return cb(new Error('no body result'))
- var binary = false
- //if the response type is an array buffer,
- //we need to convert it into a regular Buffer object
- if (isArrayBuffer(body)) {
- var array = new Uint8Array(body)
- body = new Buffer(array, 'binary')
- }
- //now check the string/Buffer response
- //and see if it has a binary BMF header
- if (isBinaryFormat(body)) {
- binary = true
- //if we have a string, turn it into a Buffer
- if (typeof body === 'string')
- body = new Buffer(body, 'binary')
- }
- //we are not parsing a binary format, just ASCII/XML/etc
- if (!binary) {
- //might still be a buffer if responseType is 'arraybuffer'
- if (Buffer.isBuffer(body))
- body = body.toString(opt.encoding)
- body = body.trim()
- }
- var result
- try {
- var type = res.headers['content-type']
- if (binary)
- result = readBinary(body)
- else if (/json/.test(type) || body.charAt(0) === '{')
- result = JSON.parse(body)
- else if (/xml/.test(type) || body.charAt(0) === '<')
- result = parseXML(body)
- else
- result = parseASCII(body)
- } catch (e) {
- cb(new Error('error parsing font '+e.message))
- cb = noop
- }
- cb(null, result)
- })
- }
- function isArrayBuffer(arr) {
- var str = Object.prototype.toString
- return str.call(arr) === '[object ArrayBuffer]'
- }
- function getBinaryOpts(opt) {
- //IE10+ and other modern browsers support array buffers
- if (xml2)
- return xtend(opt, { responseType: 'arraybuffer' })
-
- if (typeof self.XMLHttpRequest === 'undefined')
- throw new Error('your browser does not support XHR loading')
- //IE9 and XML1 browsers could still use an override
- var req = new self.XMLHttpRequest()
- req.overrideMimeType('text/plain; charset=x-user-defined')
- return xtend({
- xhr: req
- }, opt)
- }
- }).call(this,require("buffer").Buffer)
- },{"./lib/is-binary":399,"buffer":47,"parse-bmfont-ascii":281,"parse-bmfont-binary":282,"parse-bmfont-xml":283,"xhr":366,"xtend":368}],399:[function(require,module,exports){
- (function (Buffer){
- var equal = require('buffer-equal')
- var HEADER = new Buffer([66, 77, 70, 3])
- module.exports = function(buf) {
- if (typeof buf === 'string')
- return buf.substring(0, 3) === 'BMF'
- return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
- }
- }).call(this,require("buffer").Buffer)
- },{"buffer":47,"buffer-equal":48}],400:[function(require,module,exports){
- (function (Buffer){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- var _resize = _interopRequireDefault(require("./modules/resize"));
- var _resize2 = _interopRequireDefault(require("./modules/resize2"));
- var _default = function _default() {
- return {
- constants: {
- RESIZE_NEAREST_NEIGHBOR: 'nearestNeighbor',
- RESIZE_BILINEAR: 'bilinearInterpolation',
- RESIZE_BICUBIC: 'bicubicInterpolation',
- RESIZE_HERMITE: 'hermiteInterpolation',
- RESIZE_BEZIER: 'bezierInterpolation'
- },
- "class": {
- /**
- * Resizes the image to a set width and height using a 2-pass bilinear algorithm
- * @param {number} w the width to resize the image to (or Jimp.AUTO)
- * @param {number} h the height to resize the image to (or Jimp.AUTO)
- * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- resize: function resize(w, h, mode, cb) {
- if (typeof w !== 'number' || typeof h !== 'number') {
- return _utils.throwError.call(this, 'w and h must be numbers', cb);
- }
- if (typeof mode === 'function' && typeof cb === 'undefined') {
- cb = mode;
- mode = null;
- }
- if (w === this.constructor.AUTO && h === this.constructor.AUTO) {
- return _utils.throwError.call(this, 'w and h cannot both be set to auto', cb);
- }
- if (w === this.constructor.AUTO) {
- w = this.bitmap.width * (h / this.bitmap.height);
- }
- if (h === this.constructor.AUTO) {
- h = this.bitmap.height * (w / this.bitmap.width);
- }
- if (w < 0 || h < 0) {
- return _utils.throwError.call(this, 'w and h must be positive numbers', cb);
- } // round inputs
- w = Math.round(w);
- h = Math.round(h);
- if (typeof _resize2["default"][mode] === 'function') {
- var dst = {
- data: Buffer.alloc(w * h * 4),
- width: w,
- height: h
- };
- _resize2["default"][mode](this.bitmap, dst);
- this.bitmap = dst;
- } else {
- var image = this;
- var resize = new _resize["default"](this.bitmap.width, this.bitmap.height, w, h, true, true, function (buffer) {
- image.bitmap.data = Buffer.from(buffer);
- image.bitmap.width = w;
- image.bitmap.height = h;
- });
- resize.resize(this.bitmap.data);
- }
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- }).call(this,require("buffer").Buffer)
- },{"./modules/resize":401,"./modules/resize2":402,"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/utils":414,"buffer":47}],401:[function(require,module,exports){
- "use strict";
- require("core-js/modules/es.array.iterator");
- require("core-js/modules/es.array-buffer.slice");
- require("core-js/modules/es.object.to-string");
- require("core-js/modules/es.typed-array.float32-array");
- require("core-js/modules/es.typed-array.float64-array");
- require("core-js/modules/es.typed-array.uint8-array");
- require("core-js/modules/es.typed-array.copy-within");
- require("core-js/modules/es.typed-array.every");
- require("core-js/modules/es.typed-array.fill");
- require("core-js/modules/es.typed-array.filter");
- require("core-js/modules/es.typed-array.find");
- require("core-js/modules/es.typed-array.find-index");
- require("core-js/modules/es.typed-array.for-each");
- require("core-js/modules/es.typed-array.includes");
- require("core-js/modules/es.typed-array.index-of");
- require("core-js/modules/es.typed-array.iterator");
- require("core-js/modules/es.typed-array.join");
- require("core-js/modules/es.typed-array.last-index-of");
- require("core-js/modules/es.typed-array.map");
- require("core-js/modules/es.typed-array.reduce");
- require("core-js/modules/es.typed-array.reduce-right");
- require("core-js/modules/es.typed-array.reverse");
- require("core-js/modules/es.typed-array.set");
- require("core-js/modules/es.typed-array.slice");
- require("core-js/modules/es.typed-array.some");
- require("core-js/modules/es.typed-array.sort");
- require("core-js/modules/es.typed-array.subarray");
- require("core-js/modules/es.typed-array.to-locale-string");
- require("core-js/modules/es.typed-array.to-string");
- // JavaScript Image Resizer (c) 2012 - Grant Galitz
- // Released to public domain 29 July 2013: https://github.com/grantgalitz/JS-Image-Resizer/issues/4
- function Resize(widthOriginal, heightOriginal, targetWidth, targetHeight, blendAlpha, interpolationPass, resizeCallback) {
- this.widthOriginal = Math.abs(Math.floor(widthOriginal) || 0);
- this.heightOriginal = Math.abs(Math.floor(heightOriginal) || 0);
- this.targetWidth = Math.abs(Math.floor(targetWidth) || 0);
- this.targetHeight = Math.abs(Math.floor(targetHeight) || 0);
- this.colorChannels = blendAlpha ? 4 : 3;
- this.interpolationPass = Boolean(interpolationPass);
- this.resizeCallback = typeof resizeCallback === 'function' ? resizeCallback : function () {};
- this.targetWidthMultipliedByChannels = this.targetWidth * this.colorChannels;
- this.originalWidthMultipliedByChannels = this.widthOriginal * this.colorChannels;
- this.originalHeightMultipliedByChannels = this.heightOriginal * this.colorChannels;
- this.widthPassResultSize = this.targetWidthMultipliedByChannels * this.heightOriginal;
- this.finalResultSize = this.targetWidthMultipliedByChannels * this.targetHeight;
- this.initialize();
- }
- Resize.prototype.initialize = function () {
- // Perform some checks:
- if (this.widthOriginal > 0 && this.heightOriginal > 0 && this.targetWidth > 0 && this.targetHeight > 0) {
- this.configurePasses();
- } else {
- throw new Error('Invalid settings specified for the resizer.');
- }
- };
- Resize.prototype.configurePasses = function () {
- if (this.widthOriginal === this.targetWidth) {
- // Bypass the width resizer pass:
- this.resizeWidth = this.bypassResizer;
- } else {
- // Setup the width resizer pass:
- this.ratioWeightWidthPass = this.widthOriginal / this.targetWidth;
- if (this.ratioWeightWidthPass < 1 && this.interpolationPass) {
- this.initializeFirstPassBuffers(true);
- this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthInterpolatedRGBA : this.resizeWidthInterpolatedRGB;
- } else {
- this.initializeFirstPassBuffers(false);
- this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthRGBA : this.resizeWidthRGB;
- }
- }
- if (this.heightOriginal === this.targetHeight) {
- // Bypass the height resizer pass:
- this.resizeHeight = this.bypassResizer;
- } else {
- // Setup the height resizer pass:
- this.ratioWeightHeightPass = this.heightOriginal / this.targetHeight;
- if (this.ratioWeightHeightPass < 1 && this.interpolationPass) {
- this.initializeSecondPassBuffers(true);
- this.resizeHeight = this.resizeHeightInterpolated;
- } else {
- this.initializeSecondPassBuffers(false);
- this.resizeHeight = this.colorChannels === 4 ? this.resizeHeightRGBA : this.resizeHeightRGB;
- }
- }
- };
- Resize.prototype._resizeWidthInterpolatedRGBChannels = function (buffer, fourthChannel) {
- var channelsNum = fourthChannel ? 4 : 3;
- var ratioWeight = this.ratioWeightWidthPass;
- var outputBuffer = this.widthBuffer;
- var weight = 0;
- var finalOffset = 0;
- var pixelOffset = 0;
- var firstWeight = 0;
- var secondWeight = 0;
- var targetPosition; // Handle for only one interpolation input being valid for start calculation:
- for (targetPosition = 0; weight < 1 / 3; targetPosition += channelsNum, weight += ratioWeight) {
- for (finalOffset = targetPosition, pixelOffset = 0; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {
- outputBuffer[finalOffset] = buffer[pixelOffset];
- outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1];
- outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2];
- if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3];
- }
- } // Adjust for overshoot of the last pass's counter:
- weight -= 1 / 3;
- var interpolationWidthSourceReadStop;
- for (interpolationWidthSourceReadStop = this.widthOriginal - 1; weight < interpolationWidthSourceReadStop; targetPosition += channelsNum, weight += ratioWeight) {
- // Calculate weightings:
- secondWeight = weight % 1;
- firstWeight = 1 - secondWeight; // Interpolate:
- for (finalOffset = targetPosition, pixelOffset = Math.floor(weight) * channelsNum; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {
- outputBuffer[finalOffset + 0] = buffer[pixelOffset + 0] * firstWeight + buffer[pixelOffset + channelsNum + 0] * secondWeight;
- outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1] * firstWeight + buffer[pixelOffset + channelsNum + 1] * secondWeight;
- outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2] * firstWeight + buffer[pixelOffset + channelsNum + 2] * secondWeight;
- if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3] * firstWeight + buffer[pixelOffset + channelsNum + 3] * secondWeight;
- }
- } // Handle for only one interpolation input being valid for end calculation:
- for (interpolationWidthSourceReadStop = this.originalWidthMultipliedByChannels - channelsNum; targetPosition < this.targetWidthMultipliedByChannels; targetPosition += channelsNum) {
- for (finalOffset = targetPosition, pixelOffset = interpolationWidthSourceReadStop; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) {
- outputBuffer[finalOffset] = buffer[pixelOffset];
- outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1];
- outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2];
- if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3];
- }
- }
- return outputBuffer;
- };
- Resize.prototype._resizeWidthRGBChannels = function (buffer, fourthChannel) {
- var channelsNum = fourthChannel ? 4 : 3;
- var ratioWeight = this.ratioWeightWidthPass;
- var ratioWeightDivisor = 1 / ratioWeight;
- var nextLineOffsetOriginalWidth = this.originalWidthMultipliedByChannels - channelsNum + 1;
- var nextLineOffsetTargetWidth = this.targetWidthMultipliedByChannels - channelsNum + 1;
- var output = this.outputWidthWorkBench;
- var outputBuffer = this.widthBuffer;
- var trustworthyColorsCount = this.outputWidthWorkBenchOpaquePixelsCount;
- var weight = 0;
- var amountToNext = 0;
- var actualPosition = 0;
- var currentPosition = 0;
- var line = 0;
- var pixelOffset = 0;
- var outputOffset = 0;
- var multiplier = 1;
- var r = 0;
- var g = 0;
- var b = 0;
- var a = 0;
- do {
- for (line = 0; line < this.originalHeightMultipliedByChannels;) {
- output[line++] = 0;
- output[line++] = 0;
- output[line++] = 0;
- if (fourthChannel) {
- output[line++] = 0;
- trustworthyColorsCount[line / channelsNum - 1] = 0;
- }
- }
- weight = ratioWeight;
- do {
- amountToNext = 1 + actualPosition - currentPosition;
- multiplier = Math.min(weight, amountToNext);
- for (line = 0, pixelOffset = actualPosition; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetOriginalWidth) {
- r = buffer[pixelOffset];
- g = buffer[++pixelOffset];
- b = buffer[++pixelOffset];
- a = fourthChannel ? buffer[++pixelOffset] : 255; // Ignore RGB values if pixel is completely transparent
- output[line++] += (a ? r : 0) * multiplier;
- output[line++] += (a ? g : 0) * multiplier;
- output[line++] += (a ? b : 0) * multiplier;
- if (fourthChannel) {
- output[line++] += a * multiplier;
- trustworthyColorsCount[line / channelsNum - 1] += a ? multiplier : 0;
- }
- }
- if (weight >= amountToNext) {
- actualPosition += channelsNum;
- currentPosition = actualPosition;
- weight -= amountToNext;
- } else {
- currentPosition += weight;
- break;
- }
- } while (weight > 0 && actualPosition < this.originalWidthMultipliedByChannels);
- for (line = 0, pixelOffset = outputOffset; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetTargetWidth) {
- weight = fourthChannel ? trustworthyColorsCount[line / channelsNum] : 1;
- multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor;
- outputBuffer[pixelOffset] = output[line++] * multiplier;
- outputBuffer[++pixelOffset] = output[line++] * multiplier;
- outputBuffer[++pixelOffset] = output[line++] * multiplier;
- if (fourthChannel) outputBuffer[++pixelOffset] = output[line++] * ratioWeightDivisor;
- }
- outputOffset += channelsNum;
- } while (outputOffset < this.targetWidthMultipliedByChannels);
- return outputBuffer;
- };
- Resize.prototype._resizeHeightRGBChannels = function (buffer, fourthChannel) {
- var ratioWeight = this.ratioWeightHeightPass;
- var ratioWeightDivisor = 1 / ratioWeight;
- var output = this.outputHeightWorkBench;
- var outputBuffer = this.heightBuffer;
- var trustworthyColorsCount = this.outputHeightWorkBenchOpaquePixelsCount;
- var weight = 0;
- var amountToNext = 0;
- var actualPosition = 0;
- var currentPosition = 0;
- var pixelOffset = 0;
- var outputOffset = 0;
- var caret = 0;
- var multiplier = 1;
- var r = 0;
- var g = 0;
- var b = 0;
- var a = 0;
- do {
- for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {
- output[pixelOffset++] = 0;
- output[pixelOffset++] = 0;
- output[pixelOffset++] = 0;
- if (fourthChannel) {
- output[pixelOffset++] = 0;
- trustworthyColorsCount[pixelOffset / 4 - 1] = 0;
- }
- }
- weight = ratioWeight;
- do {
- amountToNext = 1 + actualPosition - currentPosition;
- multiplier = Math.min(weight, amountToNext);
- caret = actualPosition;
- for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {
- r = buffer[caret++];
- g = buffer[caret++];
- b = buffer[caret++];
- a = fourthChannel ? buffer[caret++] : 255; // Ignore RGB values if pixel is completely transparent
- output[pixelOffset++] += (a ? r : 0) * multiplier;
- output[pixelOffset++] += (a ? g : 0) * multiplier;
- output[pixelOffset++] += (a ? b : 0) * multiplier;
- if (fourthChannel) {
- output[pixelOffset++] += a * multiplier;
- trustworthyColorsCount[pixelOffset / 4 - 1] += a ? multiplier : 0;
- }
- }
- if (weight >= amountToNext) {
- actualPosition = caret;
- currentPosition = actualPosition;
- weight -= amountToNext;
- } else {
- currentPosition += weight;
- break;
- }
- } while (weight > 0 && actualPosition < this.widthPassResultSize);
- for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {
- weight = fourthChannel ? trustworthyColorsCount[pixelOffset / 4] : 1;
- multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor;
- outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);
- outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);
- outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier);
- if (fourthChannel) {
- outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor);
- }
- }
- } while (outputOffset < this.finalResultSize);
- return outputBuffer;
- };
- Resize.prototype.resizeWidthInterpolatedRGB = function (buffer) {
- return this._resizeWidthInterpolatedRGBChannels(buffer, false);
- };
- Resize.prototype.resizeWidthInterpolatedRGBA = function (buffer) {
- return this._resizeWidthInterpolatedRGBChannels(buffer, true);
- };
- Resize.prototype.resizeWidthRGB = function (buffer) {
- return this._resizeWidthRGBChannels(buffer, false);
- };
- Resize.prototype.resizeWidthRGBA = function (buffer) {
- return this._resizeWidthRGBChannels(buffer, true);
- };
- Resize.prototype.resizeHeightInterpolated = function (buffer) {
- var ratioWeight = this.ratioWeightHeightPass;
- var outputBuffer = this.heightBuffer;
- var weight = 0;
- var finalOffset = 0;
- var pixelOffset = 0;
- var pixelOffsetAccumulated = 0;
- var pixelOffsetAccumulated2 = 0;
- var firstWeight = 0;
- var secondWeight = 0;
- var interpolationHeightSourceReadStop; // Handle for only one interpolation input being valid for start calculation:
- for (; weight < 1 / 3; weight += ratioWeight) {
- for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) {
- outputBuffer[finalOffset++] = Math.round(buffer[pixelOffset++]);
- }
- } // Adjust for overshoot of the last pass's counter:
- weight -= 1 / 3;
- for (interpolationHeightSourceReadStop = this.heightOriginal - 1; weight < interpolationHeightSourceReadStop; weight += ratioWeight) {
- // Calculate weightings:
- secondWeight = weight % 1;
- firstWeight = 1 - secondWeight; // Interpolate:
- pixelOffsetAccumulated = Math.floor(weight) * this.targetWidthMultipliedByChannels;
- pixelOffsetAccumulated2 = pixelOffsetAccumulated + this.targetWidthMultipliedByChannels;
- for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) {
- outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++] * firstWeight + buffer[pixelOffsetAccumulated2++] * secondWeight);
- }
- } // Handle for only one interpolation input being valid for end calculation:
- while (finalOffset < this.finalResultSize) {
- for (pixelOffset = 0, pixelOffsetAccumulated = interpolationHeightSourceReadStop * this.targetWidthMultipliedByChannels; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) {
- outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++]);
- }
- }
- return outputBuffer;
- };
- Resize.prototype.resizeHeightRGB = function (buffer) {
- return this._resizeHeightRGBChannels(buffer, false);
- };
- Resize.prototype.resizeHeightRGBA = function (buffer) {
- return this._resizeHeightRGBChannels(buffer, true);
- };
- Resize.prototype.resize = function (buffer) {
- this.resizeCallback(this.resizeHeight(this.resizeWidth(buffer)));
- };
- Resize.prototype.bypassResizer = function (buffer) {
- // Just return the buffer passed:
- return buffer;
- };
- Resize.prototype.initializeFirstPassBuffers = function (BILINEARAlgo) {
- // Initialize the internal width pass buffers:
- this.widthBuffer = this.generateFloatBuffer(this.widthPassResultSize);
- if (!BILINEARAlgo) {
- this.outputWidthWorkBench = this.generateFloatBuffer(this.originalHeightMultipliedByChannels);
- if (this.colorChannels > 3) {
- this.outputWidthWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.heightOriginal);
- }
- }
- };
- Resize.prototype.initializeSecondPassBuffers = function (BILINEARAlgo) {
- // Initialize the internal height pass buffers:
- this.heightBuffer = this.generateUint8Buffer(this.finalResultSize);
- if (!BILINEARAlgo) {
- this.outputHeightWorkBench = this.generateFloatBuffer(this.targetWidthMultipliedByChannels);
- if (this.colorChannels > 3) {
- this.outputHeightWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.targetWidth);
- }
- }
- };
- Resize.prototype.generateFloatBuffer = function (bufferLength) {
- // Generate a float32 typed array buffer:
- try {
- return new Float32Array(bufferLength);
- } catch (error) {
- return [];
- }
- };
- Resize.prototype.generateFloat64Buffer = function (bufferLength) {
- // Generate a float64 typed array buffer:
- try {
- return new Float64Array(bufferLength);
- } catch (error) {
- return [];
- }
- };
- Resize.prototype.generateUint8Buffer = function (bufferLength) {
- // Generate a uint8 typed array buffer:
- try {
- return new Uint8Array(bufferLength);
- } catch (error) {
- return [];
- }
- };
- module.exports = Resize;
- },{"core-js/modules/es.array-buffer.slice":172,"core-js/modules/es.array.iterator":182,"core-js/modules/es.object.to-string":197,"core-js/modules/es.typed-array.copy-within":208,"core-js/modules/es.typed-array.every":209,"core-js/modules/es.typed-array.fill":210,"core-js/modules/es.typed-array.filter":211,"core-js/modules/es.typed-array.find":213,"core-js/modules/es.typed-array.find-index":212,"core-js/modules/es.typed-array.float32-array":214,"core-js/modules/es.typed-array.float64-array":215,"core-js/modules/es.typed-array.for-each":216,"core-js/modules/es.typed-array.includes":217,"core-js/modules/es.typed-array.index-of":218,"core-js/modules/es.typed-array.iterator":219,"core-js/modules/es.typed-array.join":220,"core-js/modules/es.typed-array.last-index-of":221,"core-js/modules/es.typed-array.map":222,"core-js/modules/es.typed-array.reduce":224,"core-js/modules/es.typed-array.reduce-right":223,"core-js/modules/es.typed-array.reverse":225,"core-js/modules/es.typed-array.set":226,"core-js/modules/es.typed-array.slice":227,"core-js/modules/es.typed-array.some":228,"core-js/modules/es.typed-array.sort":229,"core-js/modules/es.typed-array.subarray":230,"core-js/modules/es.typed-array.to-locale-string":231,"core-js/modules/es.typed-array.to-string":232,"core-js/modules/es.typed-array.uint8-array":233}],402:[function(require,module,exports){
- (function (Buffer){
- "use strict";
- /**
- * Copyright (c) 2015 Guyon Roche
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:</p>
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
- module.exports = {
- nearestNeighbor: function nearestNeighbor(src, dst) {
- var wSrc = src.width;
- var hSrc = src.height;
- var wDst = dst.width;
- var hDst = dst.height;
- var bufSrc = src.data;
- var bufDst = dst.data;
- for (var i = 0; i < hDst; i++) {
- for (var j = 0; j < wDst; j++) {
- var posDst = (i * wDst + j) * 4;
- var iSrc = Math.floor(i * hSrc / hDst);
- var jSrc = Math.floor(j * wSrc / wDst);
- var posSrc = (iSrc * wSrc + jSrc) * 4;
- bufDst[posDst++] = bufSrc[posSrc++];
- bufDst[posDst++] = bufSrc[posSrc++];
- bufDst[posDst++] = bufSrc[posSrc++];
- bufDst[posDst++] = bufSrc[posSrc++];
- }
- }
- },
- bilinearInterpolation: function bilinearInterpolation(src, dst) {
- var wSrc = src.width;
- var hSrc = src.height;
- var wDst = dst.width;
- var hDst = dst.height;
- var bufSrc = src.data;
- var bufDst = dst.data;
- var interpolate = function interpolate(k, kMin, vMin, kMax, vMax) {
- // special case - k is integer
- if (kMin === kMax) {
- return vMin;
- }
- return Math.round((k - kMin) * vMax + (kMax - k) * vMin);
- };
- var assign = function assign(pos, offset, x, xMin, xMax, y, yMin, yMax) {
- var posMin = (yMin * wSrc + xMin) * 4 + offset;
- var posMax = (yMin * wSrc + xMax) * 4 + offset;
- var vMin = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]); // special case, y is integer
- if (yMax === yMin) {
- bufDst[pos + offset] = vMin;
- } else {
- posMin = (yMax * wSrc + xMin) * 4 + offset;
- posMax = (yMax * wSrc + xMax) * 4 + offset;
- var vMax = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]);
- bufDst[pos + offset] = interpolate(y, yMin, vMin, yMax, vMax);
- }
- };
- for (var i = 0; i < hDst; i++) {
- for (var j = 0; j < wDst; j++) {
- var posDst = (i * wDst + j) * 4; // x & y in src coordinates
- var x = j * wSrc / wDst;
- var xMin = Math.floor(x);
- var xMax = Math.min(Math.ceil(x), wSrc - 1);
- var y = i * hSrc / hDst;
- var yMin = Math.floor(y);
- var yMax = Math.min(Math.ceil(y), hSrc - 1);
- assign(posDst, 0, x, xMin, xMax, y, yMin, yMax);
- assign(posDst, 1, x, xMin, xMax, y, yMin, yMax);
- assign(posDst, 2, x, xMin, xMax, y, yMin, yMax);
- assign(posDst, 3, x, xMin, xMax, y, yMin, yMax);
- }
- }
- },
- _interpolate2D: function _interpolate2D(src, dst, options, interpolate) {
- var bufSrc = src.data;
- var bufDst = dst.data;
- var wSrc = src.width;
- var hSrc = src.height;
- var wDst = dst.width;
- var hDst = dst.height; // when dst smaller than src/2, interpolate first to a multiple between 0.5 and 1.0 src, then sum squares
- var wM = Math.max(1, Math.floor(wSrc / wDst));
- var wDst2 = wDst * wM;
- var hM = Math.max(1, Math.floor(hSrc / hDst));
- var hDst2 = hDst * hM; // ===========================================================
- // Pass 1 - interpolate rows
- // buf1 has width of dst2 and height of src
- var buf1 = Buffer.alloc(wDst2 * hSrc * 4);
- for (var i = 0; i < hSrc; i++) {
- for (var j = 0; j < wDst2; j++) {
- // i in src coords, j in dst coords
- // calculate x in src coords
- // this interpolation requires 4 sample points and the two inner ones must be real
- // the outer points can be fudged for the edges.
- // therefore (wSrc-1)/wDst2
- var x = j * (wSrc - 1) / wDst2;
- var xPos = Math.floor(x);
- var t = x - xPos;
- var srcPos = (i * wSrc + xPos) * 4;
- var buf1Pos = (i * wDst2 + j) * 4;
- for (var k = 0; k < 4; k++) {
- var kPos = srcPos + k;
- var x0 = xPos > 0 ? bufSrc[kPos - 4] : 2 * bufSrc[kPos] - bufSrc[kPos + 4];
- var x1 = bufSrc[kPos];
- var x2 = bufSrc[kPos + 4];
- var x3 = xPos < wSrc - 2 ? bufSrc[kPos + 8] : 2 * bufSrc[kPos + 4] - bufSrc[kPos];
- buf1[buf1Pos + k] = interpolate(x0, x1, x2, x3, t);
- }
- }
- } // this._writeFile(wDst2, hSrc, buf1, "out/buf1.jpg");
- // ===========================================================
- // Pass 2 - interpolate columns
- // buf2 has width and height of dst2
- var buf2 = Buffer.alloc(wDst2 * hDst2 * 4);
- for (var _i = 0; _i < hDst2; _i++) {
- for (var _j = 0; _j < wDst2; _j++) {
- // i&j in dst2 coords
- // calculate y in buf1 coords
- // this interpolation requires 4 sample points and the two inner ones must be real
- // the outer points can be fudged for the edges.
- // therefore (hSrc-1)/hDst2
- var y = _i * (hSrc - 1) / hDst2;
- var yPos = Math.floor(y);
- var _t = y - yPos;
- var _buf1Pos = (yPos * wDst2 + _j) * 4;
- var buf2Pos = (_i * wDst2 + _j) * 4;
- for (var _k = 0; _k < 4; _k++) {
- var _kPos = _buf1Pos + _k;
- var y0 = yPos > 0 ? buf1[_kPos - wDst2 * 4] : 2 * buf1[_kPos] - buf1[_kPos + wDst2 * 4];
- var y1 = buf1[_kPos];
- var y2 = buf1[_kPos + wDst2 * 4];
- var y3 = yPos < hSrc - 2 ? buf1[_kPos + wDst2 * 8] : 2 * buf1[_kPos + wDst2 * 4] - buf1[_kPos];
- buf2[buf2Pos + _k] = interpolate(y0, y1, y2, y3, _t);
- }
- }
- } // this._writeFile(wDst2, hDst2, buf2, "out/buf2.jpg");
- // ===========================================================
- // Pass 3 - scale to dst
- var m = wM * hM;
- if (m > 1) {
- for (var _i2 = 0; _i2 < hDst; _i2++) {
- for (var _j2 = 0; _j2 < wDst; _j2++) {
- // i&j in dst bounded coords
- var r = 0;
- var g = 0;
- var b = 0;
- var a = 0;
- var realColors = 0;
- for (var _y = 0; _y < hM; _y++) {
- var _yPos = _i2 * hM + _y;
- for (var _x = 0; _x < wM; _x++) {
- var _xPos = _j2 * wM + _x;
- var xyPos = (_yPos * wDst2 + _xPos) * 4;
- var pixelAlpha = buf2[xyPos + 3];
- if (pixelAlpha) {
- r += buf2[xyPos];
- g += buf2[xyPos + 1];
- b += buf2[xyPos + 2];
- realColors++;
- }
- a += pixelAlpha;
- }
- }
- var pos = (_i2 * wDst + _j2) * 4;
- bufDst[pos] = realColors ? Math.round(r / realColors) : 0;
- bufDst[pos + 1] = realColors ? Math.round(g / realColors) : 0;
- bufDst[pos + 2] = realColors ? Math.round(b / realColors) : 0;
- bufDst[pos + 3] = Math.round(a / m);
- }
- }
- } else {
- // replace dst buffer with buf2
- dst.data = buf2;
- }
- },
- bicubicInterpolation: function bicubicInterpolation(src, dst, options) {
- var interpolateCubic = function interpolateCubic(x0, x1, x2, x3, t) {
- var a0 = x3 - x2 - x0 + x1;
- var a1 = x0 - x1 - a0;
- var a2 = x2 - x0;
- var a3 = x1;
- return Math.max(0, Math.min(255, a0 * (t * t * t) + a1 * (t * t) + a2 * t + a3));
- };
- return this._interpolate2D(src, dst, options, interpolateCubic);
- },
- hermiteInterpolation: function hermiteInterpolation(src, dst, options) {
- var interpolateHermite = function interpolateHermite(x0, x1, x2, x3, t) {
- var c0 = x1;
- var c1 = 0.5 * (x2 - x0);
- var c2 = x0 - 2.5 * x1 + 2 * x2 - 0.5 * x3;
- var c3 = 0.5 * (x3 - x0) + 1.5 * (x1 - x2);
- return Math.max(0, Math.min(255, Math.round(((c3 * t + c2) * t + c1) * t + c0)));
- };
- return this._interpolate2D(src, dst, options, interpolateHermite);
- },
- bezierInterpolation: function bezierInterpolation(src, dst, options) {
- // between 2 points y(n), y(n+1), use next points out, y(n-1), y(n+2)
- // to predict control points (a & b) to be placed at n+0.5
- // ya(n) = y(n) + (y(n+1)-y(n-1))/4
- // yb(n) = y(n+1) - (y(n+2)-y(n))/4
- // then use std bezier to interpolate [n,n+1)
- // y(n+t) = y(n)*(1-t)^3 + 3 * ya(n)*(1-t)^2*t + 3 * yb(n)*(1-t)*t^2 + y(n+1)*t^3
- // note the 3* factor for the two control points
- // for edge cases, can choose:
- // y(-1) = y(0) - 2*(y(1)-y(0))
- // y(w) = y(w-1) + 2*(y(w-1)-y(w-2))
- // but can go with y(-1) = y(0) and y(w) = y(w-1)
- var interpolateBezier = function interpolateBezier(x0, x1, x2, x3, t) {
- // x1, x2 are the knots, use x0 and x3 to calculate control points
- var cp1 = x1 + (x2 - x0) / 4;
- var cp2 = x2 - (x3 - x1) / 4;
- var nt = 1 - t;
- var c0 = x1 * nt * nt * nt;
- var c1 = 3 * cp1 * nt * nt * t;
- var c2 = 3 * cp2 * nt * t * t;
- var c3 = x2 * t * t * t;
- return Math.max(0, Math.min(255, Math.round(c0 + c1 + c2 + c3)));
- };
- return this._interpolate2D(src, dst, options, interpolateBezier);
- }
- };
- }).call(this,require("buffer").Buffer)
- },{"buffer":47}],403:[function(require,module,exports){
- (function (Buffer){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Rotates an image clockwise by an arbitrary number of degrees. NB: 'this' must be a Jimp object.
- * @param {number} deg the number of degrees to rotate the image by
- * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed
- */
- function advancedRotate(deg, mode) {
- deg %= 360;
- var rad = deg * Math.PI / 180;
- var cosine = Math.cos(rad);
- var sine = Math.sin(rad); // the final width and height will change if resize == true
- var w = this.bitmap.width;
- var h = this.bitmap.height;
- if (mode === true || typeof mode === 'string') {
- // resize the image to it maximum dimension and blit the existing image
- // onto the center so that when it is rotated the image is kept in bounds
- // http://stackoverflow.com/questions/3231176/how-to-get-size-of-a-rotated-rectangle
- // Plus 1 border pixel to ensure to show all rotated result for some cases.
- w = Math.ceil(Math.abs(this.bitmap.width * cosine) + Math.abs(this.bitmap.height * sine)) + 1;
- h = Math.ceil(Math.abs(this.bitmap.width * sine) + Math.abs(this.bitmap.height * cosine)) + 1; // Ensure destination to have even size to a better result.
- if (w % 2 !== 0) {
- w++;
- }
- if (h % 2 !== 0) {
- h++;
- }
- var c = this.cloneQuiet();
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- this.bitmap.data.writeUInt32BE(this._background, idx);
- });
- var max = Math.max(w, h, this.bitmap.width, this.bitmap.height);
- this.resize(max, max, mode);
- this.blit(c, this.bitmap.width / 2 - c.bitmap.width / 2, this.bitmap.height / 2 - c.bitmap.height / 2);
- }
- var bW = this.bitmap.width;
- var bH = this.bitmap.height;
- var dstBuffer = Buffer.alloc(this.bitmap.data.length);
- function createTranslationFunction(deltaX, deltaY) {
- return function (x, y) {
- return {
- x: x + deltaX,
- y: y + deltaY
- };
- };
- }
- var translate2Cartesian = createTranslationFunction(-(bW / 2), -(bH / 2));
- var translate2Screen = createTranslationFunction(bW / 2 + 0.5, bH / 2 + 0.5);
- for (var y = 1; y <= bH; y++) {
- for (var x = 1; x <= bW; x++) {
- var cartesian = translate2Cartesian(x, y);
- var source = translate2Screen(cosine * cartesian.x - sine * cartesian.y, cosine * cartesian.y + sine * cartesian.x);
- var dstIdx = bW * (y - 1) + x - 1 << 2;
- if (source.x >= 0 && source.x < bW && source.y >= 0 && source.y < bH) {
- var srcIdx = (bW * (source.y | 0) + source.x | 0) << 2;
- var pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx);
- dstBuffer.writeUInt32BE(pixelRGBA, dstIdx);
- } else {
- // reset off-image pixels
- dstBuffer.writeUInt32BE(this._background, dstIdx);
- }
- }
- }
- this.bitmap.data = dstBuffer;
- if (mode === true || typeof mode === 'string') {
- // now crop the image to the final size
- var _x = bW / 2 - w / 2;
- var _y = bH / 2 - h / 2;
- this.crop(_x, _y, w, h);
- }
- }
- var _default = function _default() {
- return {
- /**
- * Rotates the image clockwise by a number of degrees. By default the width and height of the image will be resized appropriately.
- * @param {number} deg the number of degrees to rotate the image by
- * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- rotate: function rotate(deg, mode, cb) {
- // enable overloading
- if (typeof mode === 'undefined' || mode === null) {
- // e.g. image.resize(120);
- // e.g. image.resize(120, null, cb);
- // e.g. image.resize(120, undefined, cb);
- mode = true;
- }
- if (typeof mode === 'function' && typeof cb === 'undefined') {
- // e.g. image.resize(120, cb);
- cb = mode;
- mode = true;
- }
- if (typeof deg !== 'number') {
- return _utils.throwError.call(this, 'deg must be a number', cb);
- }
- if (typeof mode !== 'boolean' && typeof mode !== 'string') {
- return _utils.throwError.call(this, 'mode must be a boolean or a string', cb);
- }
- advancedRotate.call(this, deg, mode, cb);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- }).call(this,require("buffer").Buffer)
- },{"@jimp/utils":414,"buffer":47}],404:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- var _default = function _default() {
- return {
- /**
- * Uniformly scales the image by a factor.
- * @param {number} f the factor to scale the image by
- * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- scale: function scale(f, mode, cb) {
- if (typeof f !== 'number') {
- return _utils.throwError.call(this, 'f must be a number', cb);
- }
- if (f < 0) {
- return _utils.throwError.call(this, 'f must be a positive number', cb);
- }
- if (typeof mode === 'function' && typeof cb === 'undefined') {
- cb = mode;
- mode = null;
- }
- var w = this.bitmap.width * f;
- var h = this.bitmap.height * f;
- this.resize(w, h, mode);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Scale the image to the largest size that fits inside the rectangle that has the given width and height.
- * @param {number} w the width to resize the image to
- * @param {number} h the height to resize the image to
- * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER)
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- scaleToFit: function scaleToFit(w, h, mode, cb) {
- if (typeof w !== 'number' || typeof h !== 'number') {
- return _utils.throwError.call(this, 'w and h must be numbers', cb);
- }
- if (typeof mode === 'function' && typeof cb === 'undefined') {
- cb = mode;
- mode = null;
- }
- var f = w / h > this.bitmap.width / this.bitmap.height ? h / this.bitmap.height : w / this.bitmap.width;
- this.scale(f, mode);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414}],405:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Creates a circle out of an image.
- * @param {function(Error, Jimp)} options (optional)
- * opacity - opacity of the shadow between 0 and 1
- * size,- of the shadow
- * blur - how blurry the shadow is
- * x- x position of shadow
- * y - y position of shadow
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- var _default = function _default() {
- return {
- shadow: function shadow() {
- var _this = this;
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var cb = arguments.length > 1 ? arguments[1] : undefined;
- if (typeof options === 'function') {
- cb = options;
- options = {};
- }
- var _options = options,
- _options$opacity = _options.opacity,
- opacity = _options$opacity === void 0 ? 0.7 : _options$opacity,
- _options$size = _options.size,
- size = _options$size === void 0 ? 1.1 : _options$size,
- _options$x = _options.x,
- x = _options$x === void 0 ? -25 : _options$x,
- _options$y = _options.y,
- y = _options$y === void 0 ? 25 : _options$y,
- _options$blur = _options.blur,
- blur = _options$blur === void 0 ? 5 : _options$blur; // clone the image
- var orig = this.clone();
- var shadow = this.clone(); // turn all it's pixels black
- shadow.scan(0, 0, shadow.bitmap.width, shadow.bitmap.height, function (x, y, idx) {
- shadow.bitmap.data[idx] = 0x00;
- shadow.bitmap.data[idx + 1] = 0x00;
- shadow.bitmap.data[idx + 2] = 0x00; // up the opacity a little,
- shadow.bitmap.data[idx + 3] = shadow.constructor.limit255(shadow.bitmap.data[idx + 3] * opacity);
- _this.bitmap.data[idx] = 0x00;
- _this.bitmap.data[idx + 1] = 0x00;
- _this.bitmap.data[idx + 2] = 0x00;
- _this.bitmap.data[idx + 3] = 0x00;
- }); // enlarge it. This creates a "shadow".
- shadow.resize(shadow.bitmap.width * size, shadow.bitmap.height * size).blur(blur); // Then blit the "shadow" onto the background and the image on top of that.
- this.composite(shadow, x, y);
- this.composite(orig, 0, 0);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414}],406:[function(require,module,exports){
- "use strict";
- require("core-js/modules/es.regexp.exec");
- require("core-js/modules/es.string.replace");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _utils = require("@jimp/utils");
- /**
- * Applies a minimum color threshold to a greyscale image. Converts image to greyscale by default
- * @param {number} options object
- * max: A number auto limited between 0 - 255
- * replace: (optional) A number auto limited between 0 - 255 (default 255)
- * autoGreyscale: (optional) A boolean whether to apply greyscale beforehand (default true)
- * @param {number} cb (optional) a callback for when complete
- * @return {this} this for chaining of methods
- */
- var _default = function _default() {
- return {
- threshold: function threshold(_ref, cb) {
- var _this = this;
- var max = _ref.max,
- _ref$replace = _ref.replace,
- replace = _ref$replace === void 0 ? 255 : _ref$replace,
- _ref$autoGreyscale = _ref.autoGreyscale,
- autoGreyscale = _ref$autoGreyscale === void 0 ? true : _ref$autoGreyscale;
- if (typeof max !== 'number') {
- return _utils.throwError.call(this, 'max must be a number', cb);
- }
- if (typeof replace !== 'number') {
- return _utils.throwError.call(this, 'replace must be a number', cb);
- }
- if (typeof autoGreyscale !== 'boolean') {
- return _utils.throwError.call(this, 'autoGreyscale must be a boolean', cb);
- }
- max = this.constructor.limit255(max);
- replace = this.constructor.limit255(replace);
- if (autoGreyscale) {
- this.greyscale();
- }
- this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) {
- var grey = _this.bitmap.data[idx] < max ? _this.bitmap.data[idx] : replace;
- _this.bitmap.data[idx] = grey;
- _this.bitmap.data[idx + 1] = grey;
- _this.bitmap.data[idx + 2] = grey;
- });
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@jimp/utils":414,"core-js/modules/es.regexp.exec":200,"core-js/modules/es.string.replace":205}],407:[function(require,module,exports){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- require("core-js/modules/es.array.map");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
- var _timm = require("timm");
- var _pluginBlit = _interopRequireDefault(require("@jimp/plugin-blit"));
- var _pluginBlur = _interopRequireDefault(require("@jimp/plugin-blur"));
- var _pluginCircle = _interopRequireDefault(require("@jimp/plugin-circle"));
- var _pluginColor = _interopRequireDefault(require("@jimp/plugin-color"));
- var _pluginContain = _interopRequireDefault(require("@jimp/plugin-contain"));
- var _pluginCover = _interopRequireDefault(require("@jimp/plugin-cover"));
- var _pluginCrop = _interopRequireDefault(require("@jimp/plugin-crop"));
- var _pluginDisplace = _interopRequireDefault(require("@jimp/plugin-displace"));
- var _pluginDither = _interopRequireDefault(require("@jimp/plugin-dither"));
- var _pluginFisheye = _interopRequireDefault(require("@jimp/plugin-fisheye"));
- var _pluginFlip = _interopRequireDefault(require("@jimp/plugin-flip"));
- var _pluginGaussian = _interopRequireDefault(require("@jimp/plugin-gaussian"));
- var _pluginInvert = _interopRequireDefault(require("@jimp/plugin-invert"));
- var _pluginMask = _interopRequireDefault(require("@jimp/plugin-mask"));
- var _pluginNormalize = _interopRequireDefault(require("@jimp/plugin-normalize"));
- var _pluginPrint = _interopRequireDefault(require("@jimp/plugin-print"));
- var _pluginResize = _interopRequireDefault(require("@jimp/plugin-resize"));
- var _pluginRotate = _interopRequireDefault(require("@jimp/plugin-rotate"));
- var _pluginScale = _interopRequireDefault(require("@jimp/plugin-scale"));
- var _pluginShadow = _interopRequireDefault(require("@jimp/plugin-shadow"));
- var _pluginThreshold = _interopRequireDefault(require("@jimp/plugin-threshold"));
- var plugins = [_pluginBlit["default"], _pluginBlur["default"], _pluginCircle["default"], _pluginColor["default"], _pluginContain["default"], _pluginCover["default"], _pluginCrop["default"], _pluginDisplace["default"], _pluginDither["default"], _pluginFisheye["default"], _pluginFlip["default"], _pluginGaussian["default"], _pluginInvert["default"], _pluginMask["default"], _pluginNormalize["default"], _pluginPrint["default"], _pluginResize["default"], _pluginRotate["default"], _pluginScale["default"], _pluginShadow["default"], _pluginThreshold["default"]];
- var _default = function _default(jimpEvChange) {
- var initializedPlugins = plugins.map(function (pluginModule) {
- var plugin = pluginModule(jimpEvChange) || {};
- if (!plugin["class"] && !plugin.constants) {
- // Default to class function
- plugin = {
- "class": plugin
- };
- }
- return plugin;
- });
- return _timm.mergeDeep.apply(void 0, (0, _toConsumableArray2["default"])(initializedPlugins));
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/helpers/toConsumableArray":19,"@jimp/plugin-blit":380,"@jimp/plugin-blur":382,"@jimp/plugin-circle":383,"@jimp/plugin-color":384,"@jimp/plugin-contain":385,"@jimp/plugin-cover":386,"@jimp/plugin-crop":387,"@jimp/plugin-displace":388,"@jimp/plugin-dither":389,"@jimp/plugin-fisheye":390,"@jimp/plugin-flip":391,"@jimp/plugin-gaussian":392,"@jimp/plugin-invert":393,"@jimp/plugin-mask":394,"@jimp/plugin-normalize":395,"@jimp/plugin-print":396,"@jimp/plugin-resize":400,"@jimp/plugin-rotate":403,"@jimp/plugin-scale":404,"@jimp/plugin-shadow":405,"@jimp/plugin-threshold":406,"core-js/modules/es.array.map":184,"timm":356}],408:[function(require,module,exports){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
- var _bmpJs = _interopRequireDefault(require("bmp-js"));
- var _utils = require("@jimp/utils");
- var MIME_TYPE = 'image/bmp';
- var MIME_TYPE_SECOND = 'image/x-ms-bmp';
- function toAGBR(image) {
- return (0, _utils.scan)(image, 0, 0, image.bitmap.width, image.bitmap.height, function (x, y, index) {
- var red = this.bitmap.data[index + 0];
- var green = this.bitmap.data[index + 1];
- var blue = this.bitmap.data[index + 2];
- var alpha = this.bitmap.data[index + 3];
- this.bitmap.data[index + 0] = alpha;
- this.bitmap.data[index + 1] = blue;
- this.bitmap.data[index + 2] = green;
- this.bitmap.data[index + 3] = red;
- }).bitmap;
- }
- function fromAGBR(bitmap) {
- return (0, _utils.scan)({
- bitmap: bitmap
- }, 0, 0, bitmap.width, bitmap.height, function (x, y, index) {
- var alpha = this.bitmap.data[index + 0];
- var blue = this.bitmap.data[index + 1];
- var green = this.bitmap.data[index + 2];
- var red = this.bitmap.data[index + 3];
- this.bitmap.data[index + 0] = red;
- this.bitmap.data[index + 1] = green;
- this.bitmap.data[index + 2] = blue;
- this.bitmap.data[index + 3] = bitmap.is_with_alpha ? alpha : 0xff;
- }).bitmap;
- }
- var decode = function decode(data) {
- return fromAGBR(_bmpJs["default"].decode(data));
- };
- var encode = function encode(image) {
- return _bmpJs["default"].encode(toAGBR(image)).data;
- };
- var _default = function _default() {
- var _decoders, _encoders;
- return {
- mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['bmp']),
- constants: {
- MIME_BMP: MIME_TYPE,
- MIME_X_MS_BMP: MIME_TYPE_SECOND
- },
- decoders: (_decoders = {}, (0, _defineProperty2["default"])(_decoders, MIME_TYPE, decode), (0, _defineProperty2["default"])(_decoders, MIME_TYPE_SECOND, decode), _decoders),
- encoders: (_encoders = {}, (0, _defineProperty2["default"])(_encoders, MIME_TYPE, encode), (0, _defineProperty2["default"])(_encoders, MIME_TYPE_SECOND, encode), _encoders)
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/utils":414,"bmp-js":29}],409:[function(require,module,exports){
- (function (Buffer){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
- var _omggif = _interopRequireDefault(require("omggif"));
- var MIME_TYPE = 'image/gif';
- var _default = function _default() {
- return {
- mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['gif']),
- constants: {
- MIME_GIF: MIME_TYPE
- },
- decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (data) {
- var gifObj = new _omggif["default"].GifReader(data);
- var gifData = Buffer.alloc(gifObj.width * gifObj.height * 4);
- gifObj.decodeAndBlitFrameRGBA(0, gifData);
- return {
- data: gifData,
- width: gifObj.width,
- height: gifObj.height
- };
- })
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- }).call(this,require("buffer").Buffer)
- },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"buffer":47,"omggif":264}],410:[function(require,module,exports){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
- var _jpegJs = _interopRequireDefault(require("jpeg-js"));
- var _utils = require("@jimp/utils");
- var MIME_TYPE = 'image/jpeg';
- var _default = function _default() {
- return {
- mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['jpeg', 'jpg', 'jpe']),
- constants: {
- MIME_JPEG: MIME_TYPE
- },
- decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, _jpegJs["default"].decode),
- encoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (image) {
- return _jpegJs["default"].encode(image.bitmap, image._quality).data;
- }),
- "class": {
- // The quality to be used when saving JPEG images
- _quality: 100,
- /**
- * Sets the quality of the image when saving as JPEG format (default is 100)
- * @param {number} n The quality to use 0-100
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- quality: function quality(n, cb) {
- if (typeof n !== 'number') {
- return _utils.throwError.call(this, 'n must be a number', cb);
- }
- if (n < 0 || n > 100) {
- return _utils.throwError.call(this, 'n must be a number 0 - 100', cb);
- }
- this._quality = Math.round(n);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/utils":414,"jpeg-js":259}],411:[function(require,module,exports){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
- var _pngjs = require("pngjs");
- var _utils = require("@jimp/utils");
- var MIME_TYPE = 'image/png'; // PNG filter types
- var PNG_FILTER_AUTO = -1;
- var PNG_FILTER_NONE = 0;
- var PNG_FILTER_SUB = 1;
- var PNG_FILTER_UP = 2;
- var PNG_FILTER_AVERAGE = 3;
- var PNG_FILTER_PATH = 4;
- var _default = function _default() {
- return {
- mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['png']),
- constants: {
- MIME_PNG: MIME_TYPE,
- PNG_FILTER_AUTO: PNG_FILTER_AUTO,
- PNG_FILTER_NONE: PNG_FILTER_NONE,
- PNG_FILTER_SUB: PNG_FILTER_SUB,
- PNG_FILTER_UP: PNG_FILTER_UP,
- PNG_FILTER_AVERAGE: PNG_FILTER_AVERAGE,
- PNG_FILTER_PATH: PNG_FILTER_PATH
- },
- hasAlpha: (0, _defineProperty2["default"])({}, MIME_TYPE, true),
- decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, _pngjs.PNG.sync.read),
- encoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (data) {
- var png = new _pngjs.PNG({
- width: data.bitmap.width,
- height: data.bitmap.height
- });
- png.data = data.bitmap.data;
- return _pngjs.PNG.sync.write(png, {
- width: data.bitmap.width,
- height: data.bitmap.height,
- deflateLevel: data._deflateLevel,
- deflateStrategy: data._deflateStrategy,
- filterType: data._filterType,
- colorType: typeof data._colorType === 'number' ? data._colorType : data._rgba ? 6 : 2,
- inputHasAlpha: data._rgba
- });
- }),
- "class": {
- _deflateLevel: 9,
- _deflateStrategy: 3,
- _filterType: PNG_FILTER_AUTO,
- _colorType: null,
- /**
- * Sets the deflate level used when saving as PNG format (default is 9)
- * @param {number} l Deflate level to use 0-9. 0 is no compression. 9 (default) is maximum compression.
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- deflateLevel: function deflateLevel(l, cb) {
- if (typeof l !== 'number') {
- return _utils.throwError.call(this, 'l must be a number', cb);
- }
- if (l < 0 || l > 9) {
- return _utils.throwError.call(this, 'l must be a number 0 - 9', cb);
- }
- this._deflateLevel = Math.round(l);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Sets the deflate strategy used when saving as PNG format (default is 3)
- * @param {number} s Deflate strategy to use 0-3.
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- deflateStrategy: function deflateStrategy(s, cb) {
- if (typeof s !== 'number') {
- return _utils.throwError.call(this, 's must be a number', cb);
- }
- if (s < 0 || s > 3) {
- return _utils.throwError.call(this, 's must be a number 0 - 3', cb);
- }
- this._deflateStrategy = Math.round(s);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Sets the filter type used when saving as PNG format (default is automatic filters)
- * @param {number} f The quality to use -1-4.
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- filterType: function filterType(f, cb) {
- if (typeof f !== 'number') {
- return _utils.throwError.call(this, 'n must be a number', cb);
- }
- if (f < -1 || f > 4) {
- return _utils.throwError.call(this, 'n must be -1 (auto) or a number 0 - 4', cb);
- }
- this._filterType = Math.round(f);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- },
- /**
- * Sets the color type used when saving as PNG format
- * @param {number} s color type to use 0, 2, 4, 6.
- * @param {function(Error, Jimp)} cb (optional) a callback for when complete
- * @returns {Jimp} this for chaining of methods
- */
- colorType: function colorType(s, cb) {
- if (typeof s !== 'number') {
- return _utils.throwError.call(this, 's must be a number', cb);
- }
- if (s !== 0 && s !== 2 && s !== 4 && s !== 6) {
- return _utils.throwError.call(this, 's must be a number 0, 2, 4, 6.', cb);
- }
- this._colorType = Math.round(s);
- if ((0, _utils.isNodePattern)(cb)) {
- cb.call(this, null, this);
- }
- return this;
- }
- }
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/utils":414,"pngjs":308}],412:[function(require,module,exports){
- (function (Buffer){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
- var _utif = _interopRequireDefault(require("utif"));
- var MIME_TYPE = 'image/tiff';
- var _default = function _default() {
- return {
- mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['tiff', 'tif']),
- constants: {
- MIME_TIFF: MIME_TYPE
- },
- decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (data) {
- var ifds = _utif["default"].decode(data);
- var page = ifds[0];
- _utif["default"].decodeImages(data, ifds);
- var rgba = _utif["default"].toRGBA8(page);
- return {
- data: Buffer.from(rgba),
- width: page.t256[0],
- height: page.t257[0]
- };
- }),
- encoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (image) {
- var tiff = _utif["default"].encodeImage(image.bitmap.data, image.bitmap.width, image.bitmap.height);
- return Buffer.from(tiff);
- })
- };
- };
- exports["default"] = _default;
- module.exports = exports.default;
- }).call(this,require("buffer").Buffer)
- },{"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/interopRequireDefault":10,"buffer":47,"utif":361}],413:[function(require,module,exports){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports["default"] = void 0;
- var _timm = require("timm");
- var _jpeg = _interopRequireDefault(require("@jimp/jpeg"));
- var _png = _interopRequireDefault(require("@jimp/png"));
- var _bmp = _interopRequireDefault(require("@jimp/bmp"));
- var _tiff = _interopRequireDefault(require("@jimp/tiff"));
- var _gif = _interopRequireDefault(require("@jimp/gif"));
- var _default = function _default() {
- return (0, _timm.mergeDeep)((0, _jpeg["default"])(), (0, _png["default"])(), (0, _bmp["default"])(), (0, _tiff["default"])(), (0, _gif["default"])());
- };
- exports["default"] = _default;
- module.exports = exports.default;
- },{"@babel/runtime/helpers/interopRequireDefault":10,"@jimp/bmp":408,"@jimp/gif":409,"@jimp/jpeg":410,"@jimp/png":411,"@jimp/tiff":412,"timm":356}],414:[function(require,module,exports){
- "use strict";
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isNodePattern = isNodePattern;
- exports.throwError = throwError;
- exports.scan = scan;
- exports.scanIterator = scanIterator;
- var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
- require("regenerator-runtime/runtime");
- var _marked =
- /*#__PURE__*/
- _regenerator["default"].mark(scanIterator);
- function isNodePattern(cb) {
- if (typeof cb === 'undefined') {
- return false;
- }
- if (typeof cb !== 'function') {
- throw new TypeError('Callback must be a function');
- }
- return true;
- }
- function throwError(error, cb) {
- if (typeof error === 'string') {
- error = new Error(error);
- }
- if (typeof cb === 'function') {
- return cb.call(this, error);
- }
- throw error;
- }
- function scan(image, x, y, w, h, f) {
- // round input
- x = Math.round(x);
- y = Math.round(y);
- w = Math.round(w);
- h = Math.round(h);
- for (var _y = y; _y < y + h; _y++) {
- for (var _x = x; _x < x + w; _x++) {
- var idx = image.bitmap.width * _y + _x << 2;
- f.call(image, _x, _y, idx);
- }
- }
- return image;
- }
- function scanIterator(image, x, y, w, h) {
- var _y, _x, idx;
- return _regenerator["default"].wrap(function scanIterator$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- // round input
- x = Math.round(x);
- y = Math.round(y);
- w = Math.round(w);
- h = Math.round(h);
- _y = y;
- case 5:
- if (!(_y < y + h)) {
- _context.next = 17;
- break;
- }
- _x = x;
- case 7:
- if (!(_x < x + w)) {
- _context.next = 14;
- break;
- }
- idx = image.bitmap.width * _y + _x << 2;
- _context.next = 11;
- return {
- x: _x,
- y: _y,
- idx: idx,
- image: image
- };
- case 11:
- _x++;
- _context.next = 7;
- break;
- case 14:
- _y++;
- _context.next = 5;
- break;
- case 17:
- case "end":
- return _context.stop();
- }
- }
- }, _marked);
- }
- },{"@babel/runtime/helpers/interopRequireDefault":10,"@babel/runtime/regenerator":21,"regenerator-runtime/runtime":332}]},{},[379])(379)
- });
|